t sql根据行的日期派生列

时间:2018-11-20 19:40:08

标签: sql sql-server tsql pivot

我很抱歉提出这样一个问题,我确信已经多次回答了这个问题,但是我不太敢说出来去搜索它。甚至链接到类似问题也将不胜感激。

如果我有一个像这样的表:

+----+----------+-----+
|Name|Date      |Score|
+----+----------+-----+
| Tom|2018-20-11|  100|
| Tom|2018-13-11|   95|
+----+----------+-----+

我将如何查询该信息,以便每一行都显示今天的分数列,一周前的分数等等?在此示例中,示例数据为一行,例如

+----+----------+-----------+
|Name|ScoreToday|Score-7Days|
+----+----------+-----------+
| Tom|       100|         95|
+----+----------+-----------+

我看到通过交叉申请购买解决了类似的问题,但无法解决。感谢您的帮助:)

一些示例代码:

if exists (select * from sys.tables where name = 'test') drop table test
go
create table test (
    Name varchar(128)
    , AsAt datetime
    , Score int
)

insert test values ('Tom', getdate(), 87)
    , ('Tom', getdate() - 2, 100)
    , ('Tom', getdate() - 7, 95)
    , ('Tom', getdate() - 1, 81)
    , ('Tom', getdate() - 30, 95)

1 个答案:

答案 0 :(得分:0)

我认为您正在寻找

CREATE TABLE T
    ([Name] varchar(4), [Date] datetime, [Score] int);

INSERT INTO T
    ([Name], [Date], [Score])
VALUES
    ('Tom', '2018-11-20 00:00:00', 100),
    ('Tom', '2018-11-13 00:00:00', 95),
    ('Sami', '2018-11-13 00:00:00', 55),
    ('Sami', '2018-11-15 00:00:00', 44);

DECLARE @Dates NVARCHAR(MAX) = '';
DECLARE @SQL NVARCHAR(MAX);
SELECT @Dates = @Dates + ',' + QUOTENAME([Date])
FROM T
GROUP BY [Date];

SET @Dates = STUFF(@Dates, 1, 1, '');

SET @SQL = N' SELECT * FROM(SELECT * FROM T) TT PIVOT( MAX(Score) FOR [Date] IN ('+ @Dates +')) PVT;';
EXECUTE sp_executesql @SQL;

返回:

+------+---------------------+---------------------+---------------------+
| Name | Nov 13 2018 12:00AM | Nov 15 2018 12:00AM | Nov 20 2018 12:00AM |
+------+---------------------+---------------------+---------------------+
| Sami |                  55 |                  44 |                     |
| Tom  |                  95 |                     |                 100 |
+------+---------------------+---------------------+---------------------+

Demo