在sql查询中动态生成列标题

时间:2013-11-14 07:06:52

标签: sql-server sql-server-2008

我有一个user_log_table,其列为

 Userid         logintime             browsername
   1        2013/10/01 00:10:10         Chrome 
   1        2013/10/01 17:23:10         Chrome 
   1        2013/10/01 00:30:41         Mozilla
   1        2013/10/02 05:10:52         IE
   3        2013/10/02 09:10:25         Chrome 
   3        2013/10/03 10:10:18         Safari
   1        2013/10/03 13:10:35         Chrome 

我想要一个应该将输出显示为

的查询
  Userid   browser  01/10    02/10   03/10 
   1       Chrome     2       0       1
   1       Mozilla    1       0       0
   1       IE         0       1       0
   3       Chrome     0       1       0
   3       Safari     0       0       1

请注意,浏览器名称不固定,动态,......

我已尝试将查询视为

SELECT userid, browser, Day(logintime) as LoginDay, COUNT(logintime) as Num 
FROM   user_log_table  
GROUP BY  userid, browser, Day(logintime)

但没有找到我想要的结果.. 我可以获得上面的列标题和数据吗?

3 个答案:

答案 0 :(得分:2)

我在不同时间看到了这个动态枢轴问题。我有它。经过大量的搜索,我找到了一个解决方案,对我来说很有用。它不是那么优雅,但它救了我。我所做的是首先在临时表中准备数据,之后我动态创建枢轴字符串(在您的情况下是DD-MM)将其分配给变量。 最后我构造了一个sql字符串来作为动态sql执行。

我使用了您的示例数据,似乎有效。希望这有帮助

select 
    userid,
         browsername, 
         CAST(day(logintime) as nvarchar(2)) + '-' + CAST(Month(logintime) AS nVARCHAR(2))  AS period  
INTO #TMP
from user_log_table order by 1

DECLARE @cols AS NVARCHAR(MAX), @query  AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ',' 
                    + QUOTENAME(convert(varchar(10), period, 120)) 
                from #TMP order by 1
        FOR XML PATH(''), TYPE
        ).value('.', 'NVARCHAR(MAX)') 
    ,1,1,'')

set @query = 'SELECT userid, browsername,' + @cols + ' from 
         (
            select userid, browsername, period
            from #TMP
        ) x
        pivot 
        (
            count(period)
            for period in (' + @cols + ')
        ) p '
exec(@query)
drop table #TMP

答案 1 :(得分:1)

如下所示,或者您可以在MS SQL中使用PIVOT

SQLFiddle demo

SELECT browsername,
       SUM(CASE WHEN DAY(logintime) = 1 THEN 1 ELSE 0 END) as [01/10],
       SUM(CASE WHEN DAY(logintime) = 2 THEN 1 ELSE 0 END) as [02/10],
       SUM(CASE WHEN DAY(logintime) = 3 THEN 1 ELSE 0 END) as [03/10],
       ...
       SUM(CASE WHEN DAY(logintime) = 31 THEN 1 ELSE 0 END) as [31/10]

FROM user_log_table
GROUP BY browsername

答案 2 :(得分:0)

DECLARE @cols VARCHAR(100),@SQL VARCHAR(MAX)
select @cols = STUFF((SELECT distinct ',' +
                        QUOTENAME(convert(varchar(10),LoginTime,103))
                      FROM 
                      user_log_table
                      FOR XML PATH(''), TYPE
                     ).value('.', 'NVARCHAR(MAX)') 
                        , 1, 1, '');
SET @SQL = 'SELECT *
FROM
(
  SELECT
    Userid,
    browsername,
    convert(varchar(10),LoginTime,103) LoginDay
  FROM user_log_table xx
) AS t
PIVOT 
(
  count(LoginDay) 
  FOR LoginDay IN( '+@cols+' ) ) AS p ; ' 

  EXEC (@SQL)