【发布时间】:2020-07-14 14:27:27
【问题描述】:
表:
create table produts_1164
(
product_id int,
new_price int,
change_date date
);
insert into produts_1164
values (1, 20, '2019-08-14'),
(2, 50, '2019-08-14'),
(1, 30, '2019-08-15'),
(1, 35, '2019-08-16'),
(2, 65, '2019-08-17'),
(3, 20, '2019-08-18');
问题:写一个SQL查询查找2019-08-16所有产品的价格。假设所有产品在任何变化之前的价格都是 10。
这是我的解决方案:
select product_id, new_price as price
from products
where (product_id, change_date) in (select product_id, max(change_date)
from products
where change_date <= '2019-08-16'
group by product_id)
union
select product_id, 10 as price
from products
where product_id not in (select distinct product_id
from products
where change_date <= '2019-08-16');
但我收到此错误:
[42000] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]在预期条件的上下文中指定的非布尔类型表达式,靠近“,”。 (4145) (SQLExecDirectW)
对此有任何想法吗?谢谢
【问题讨论】:
-
我不认为你可以有多个列与 sqlserver 中的 IN 相比。
标签: sql sql-server tsql greatest-n-per-group window-functions