我有一个名为'LoginSession'的表,其中包含以下字段
id
CreatedDate
UserAgent [which stores browser name as a string ]
我想编写一个查询来获取特定时间段内每个浏览器的计数。
我使用了以下查询
WITH BrowserShortCode_CTE AS(
SELECT UserAgent,
case
when Replace(UserAgent, ' ', '') like '%MSIE10.0%' then 'Internet Explorer 10'
when Replace(UserAgent, ' ', '') like '%MSIE9.0%' then 'Internet Explorer 9'
when Replace(UserAgent, ' ', '') like '%MSIE8.0%' then 'Internet Explorer 8'
when Replace(UserAgent, ' ', '') like '%MSIE7.0%' then 'Internet Explorer 7'
else 'Others'
end as BrowserName
FROM LoginSession
WHERE
CreatedDate > '2017-01-01'
AND CreatedDate < '2017-01-10'
)
SELECT Count(0) as TotalCount, [BrowserName] FROM BrowserShortCode_CTE
GROUP BY BrowserName
ORDER BY TotalCount DESC
将结果返回为
Internet Explorer 10 100
Others 95
Internet Explorer 9 5
Internet Explorer 8 2
Internet Explorer 7 1
如何将一个字段CreatedDate添加到分组中,并输出
Date BrowserName Totalcount
,即每天浏览器明智使用情况的总和。
答案 0 :(得分:1)
WITH BrowserShortCode_CTE AS(
SELECT UserAgent,
case
when Replace(UserAgent, ' ', '') like '%MSIE10.0%' then 'Internet Explorer 10'
when Replace(UserAgent, ' ', '') like '%MSIE9.0%' then 'Internet Explorer 9'
when Replace(UserAgent, ' ', '') like '%MSIE8.0%' then 'Internet Explorer 8'
when Replace(UserAgent, ' ', '') like '%MSIE7.0%' then 'Internet Explorer 7'
else 'Others'
end as BrowserName,
CAST(CreatedDate as DATE) as CreatedDate
FROM LoginSession
WHERE
CreatedDate > '2017-01-01'
AND CreatedDate < '2017-01-10'
)
SELECT Count(0) as TotalCount, [BrowserName], CreatedDate FROM BrowserShortCode_CTE
GROUP BY BrowserName, CreatedDate
ORDER BY CreatedDate, TotalCount DESC