以表格格式显示结果集 -- SQL

Display resultset in tabular format -- in SQL

我有以下 table:

user_id    document_id    date
------------------------------------
1           1             2016-01-01
1           2             2016-01-01
1           3             2016-01-02
2           4             2016-01-01
2           5             2016-01-02
3           6             2016-01-02
3           7             2016-01-02
3           8             2016-01-02
3           9             2016-01-03
3          10             2016-01-03
3          11             2016-01-04
3           9             2016-01-04

是否有可能 - 在 SQL - 以表格格式获取每个用户每天查看的文档数量?

date          user_id_1    user_id_2    user_3
----------------------------------------------
2016-01-01    2            1            0
2016-01-02    1            1            3
2016-01-03    0            0            2
2016-01-04    0            0            2

通常我会使用任何脚本语言通过遍历结果集来创建它,但在这种特殊情况下我不能。由于限制,我只能访问 SQL 服务器。

如果可能的话,我们将不胜感激。

因为不知道你的table怎么叫,所以就叫[YourTableNameGoesHere]:

DECLARE @userstring AS nvarchar(max),
        @columns AS nvarchar(max),
        @sql AS nvarchar(max)

SELECT @userstring = stuff((select distinct ',' + quotename([user_id]) from [YourTableNameGoesHere] for xml path(''), type).value('.', 'nvarchar(max)'), 1, 1, '');
SELECT @columns = '[date],' + stuff((select distinct ',' + quotename([user_id]) + ' as ' + quotename('user_id_'+CAST([user_id] as nvarchar(10))) from [YourTableNameGoesHere] for xml path(''), type).value('.', 'nvarchar(max)'), 1, 1, '');

SELECT @sql = '
select '+@columns+'
from (select [date],
            [user_id],
            document_id
        from [YourTableNameGoesHere]) src 
pivot (COUNT(document_id) for [user_id] in ('+@userstring+')
) pvt'

EXECUTE(@sql)

输出为:

date       user_id_1   user_id_2   user_id_3
---------- ----------- ----------- -----------
2016-01-01 2           1           0
2016-01-02 1           1           3
2016-01-03 0           0           2
2016-01-04 0           0           2

(4 row(s) affected)