我有一个包含4个不同标识符的表,一个日期和一个数字列,如:
ID1 | ID2 | ID3 | ID4 | my_date | in_stock
A | A | A | C | 06.06.2020 | 2880
A | A | A | C | 05.06.2020 | 2880
A | A | A | D | 06.06.2020 | 5000
A | A | A | D | 05.06.2020 | 6000
我想从中创建一种透视表,如下所示:
ID1 | ID2 | ID3 | ID4 | 05.06.2020| 06.06.2020
A | A | A | C | 2880 | 2880
A | A | A | D | 6000 | 5000
这应该是过去10天左右创建,所以至关重要的是我不必手动设置日期。我试过用pivot做些什么,但没有成功,所以我改用pivot做这项工作 CASE WHEN
如下所示:
SELECT ID, ID2, ID3, ID4,
SUM(CASE WHEN my_date = DATEADD(DAY, -0, (SELECT MAX(my_date) FROM my_table)) then in_stock END) DATEADD(DAY, 0, (SELECT MAX(my_date) FROM my_table)),
SUM(CASE WHEN my_date = DATEADD(DAY, -1, (SELECT MAX(my_date) FROM my_table)) then in_stock END) DATEADD(DAY, -1, (SELECT MAX(my_date) FROM my_table))
FROM
(
SELECT ID, ID2, my_date, ID3, in_stock, ID4
FROM RIAMDB.dbo.my_table my_table
WHERE (my_date>DATEADD(DAY, -2, (SELECT MAX(my_date) FROM my_table)))
) src
GROUP BY ID, ID2, ID3, ID4
但我现在还是不明白
Msg 102, Level 15, State 1, Line 2
Incorrect syntax near 'DAY'.
Msg 102, Level 15, State 1, Line 2
Incorrect syntax near ')'.
Msg 102, Level 15, State 1, Line 3
Incorrect syntax near ')'.
Msg 102, Level 15, State 1, Line 3
Incorrect syntax near ')'.
Msg 102, Level 15, State 1, Line 9
Incorrect syntax near 'src'.
你们是如何处理这个问题的,是正确的方法,还是以某种方式使用pivot?还是有什么问题
1条答案
按热度按时间vcirk6k61#
似乎你在寻找一个动态的支点
例子
退货
编辑-上次更新-下次询问新问题
退货