查找价格更改日期最接近更换日期的数据

Find data where Price change date is closest to replacement date

数据看起来像

PONum ReplacementDate PriceChangeDate PcrPreviousPriceValue PcrPriceValue
90358 2022-01-10T06:16:17.420000 2022-01-12 08:19:49.746500 483.93 483.07
90358 2022-01-10T06:16:17.420000 2020-04-19 08:25:45.122000 332.19 332.84
90358 2022-01-10T06:16:17.420000 2020-06-20 01:27:55.657500 434.56 430.18
90358 2022-01-10T06:16:17.420000 2021-01-20 16:53:31.762600 403.81 399.75

预期结果:

PONum ReplacementDate PriceChangeDate PcrPreviousPriceValue PcrPriceValue
90358 2022-01-10T06:16:17.420000 2021-01-20 16:53:31.762600 403.81 399.75

我在SQL中知道可以使用服务器交叉应用来获取数据,我们如何在GBQ中做同样的事情?

SELECT top 1 * FROM Your_Table_Name ORDER BY DATEDIFF(SECOND, [PriceChangeDate], [ReplacementDate]) / 1000

假设价格变化不超过每天一次。

WITH CTE AS (
SELECT YT.*, 
 row_number() over (PARTITION BY PONum ORDER by DATE_DIFF(priceChangeDate, ReplacementDate, DAY) RN
FROM YourTable YT)

SELECT * 
FROM CTE 
WHERE RN=1

--- 根据评论第二个问题: --- 不需要额外的分析开销:只是一个简单的 where 子句。现在我们可以在需要时保留分析,我们只是不使用行号而是使用简单的 whereclause。

WITH CTE AS (SELECT 90358 PONum, 20220110061617420000 ReplacementDate, 20220112081949746500 PriceChangeDate,    483.93 PcrPreviousPriceValue,   483.07 PcrPriceValue UNION ALL
SELECT 90358 PONum, 20220110061617420000 ReplacementDate, 20200419082545122000 PriceChangeDate, 332.19 PcrPreviousPriceValue,   332.84 PcrPriceValue UNION ALL
SELECT 90358 PONum, 20220110061617420000 ReplacementDate, 20200620012755657500 PriceChangeDate, 434.56 PcrPreviousPriceValue,   430.18 PcrPriceValue UNION ALL
SELECT 90358 PONum, 20220110061617420000 ReplacementDate, 20210120165331762600 PriceChangeDate, 403.81 PcrPreviousPriceValue,   399.75 PcrPriceValue)

SELECT * FROM CTE
WHERE PriceChangeDate <= REPLACEMENTDATE 

给我们:

+-------+----------------------+----------------------+-----------------------+---------------+
| PONum |   ReplacementDate    |   PriceChangeDate    | PcrPreviousPriceValue | PcrPriceValue |
+-------+----------------------+----------------------+-----------------------+---------------+
| 90358 | 20220110061617420000 | 20200419082545122000 |                332.19 |        332.84 |
| 90358 | 20220110061617420000 | 20200620012755657500 |                434.56 |        430.18 |
| 90358 | 20220110061617420000 | 20210120165331762600 |                403.81 |        399.75 |
+-------+----------------------+----------------------+-----------------------+---------------+

所以你只需要 一个简单的查询:

SELECT * 
FROM YourTable YT
WHERE PriceChangeDate <= REPLACEMENTDATE