在SQL查询动态生成的列标题(Dynamically Generated Column headin

2019-10-18 23:42发布

我有有列作为一个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

请注意,Browsername是不固定的,它的动态,...

我曾尝试与查询作为

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

但没有找到的结果,因为我想...我能得到列如上标题,太数据?

Answer 1:

我看到这个充满活力的支点问题不同的时间。 而且我也必须这样做。 搜索了很多后,我来taht为我的伟大工程的解决方案。 它不是那么优雅,但它救了我。 我要做的就是先在一个临时表准备数据,在那之后我动态创建枢轴字符串(在你的情况下,它是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


Answer 2:

像下面或者你可以使用这个PIVOT在MS SQL:

SQLFiddle演示

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


Answer 3:

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)    


文章来源: Dynamically Generated Column headings in sql query