1

我有一个 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)

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

4

3 回答 3

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
于 2013-11-14T07:53:25.680 回答
1

类似于以下内容,或者您​​可以在 MS SQL 中将其与PIVOT一起使用:

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
于 2013-11-14T07:27:18.927 回答
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)    
于 2013-11-14T07:52:44.693 回答