我有一个数据表:
ProductNum | ProductVariation | Past_Price | Current_Price | Order_Date
------------ ------------------ ------------ --------------- ---------------------
1 33 96.05 100.10 2014-01-01 00:00:00
1 33 97.65 100.10 2014-12-03 12:34:52
1 33 98.98 100.10 2015-01-02 05:50:32
1 33 99.98 100.10 2016-03-02 06:50:43
1 33 100.01 100.10 2016-12-12 06:05:43
1 33 100.05 100.10 2017-01-02 05:34:43
我想知道是否可以查询行,以便我们获得日期最接近 12 月 31 日,{Year} 的行?
所以输出将是:
ProductNum | ProductVariation | Past_Price | Current_Price | Order_Date
------------ ------------------ ------------ --------------- ---------------------
1 33 98.98 100.10 2015-01-02 05:50:32
1 33 99.98 100.10 2016-03-02 06:50:43
1 33 100.01 100.10 2017-01-02 05:34:43
每个订单最接近 {Year} 12 月 31 日,年份:2014,2015,2016
最佳答案
您可以按日期差异排序并获取每年的前 1 行。
对于SqlServer:
DECLARE @year2014 datetime2 = '2014-12-31 12:00:00';
DECLARE @year2015 datetime2 = '2015-12-31 12:00:00';
DECLARE @year2016 datetime2 = '2016-12-31 12:00:00';
select * from (
select top(1) * from products
order by abs(datediff(second, @year2014, Order_Date))
) as p
union all
select * from (
select top(1) * from products
order by abs(datediff(second, @year2015, Order_Date))
)as p
union all
select * from (
select top(1) * from products
order by abs(datediff(second, @year2016, Order_Date))
) as p
根据需要更改 12 月 31 日的时间。
对于MySql:
set @year2014 = '2014-12-31 12:00:00';
set @year2015 = '2015-12-31 12:00:00';
set @year2016= '2016-12-31 12:00:00';
select * from (
select * from products
order by abs(TIMESTAMPDIFF(second, @year2014, Order_Date)) limit 1
) as p
union all
select * from (
select * from products
order by abs(TIMESTAMPDIFF(second, @year2015, Order_Date)) limit 1
)as p
union all
select * from (
select * from products
order by abs(TIMESTAMPDIFF(second, @year2016, Order_Date)) limit 1
) as p
关于mysql - SQL Server : Select rows with dates that correspond to end of year and calculate price,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54120222/