场景:我有一个表格Browsers
,每次打开浏览器时都会填充相关日期:
BrowserName Date
-------------------------------------
Firefox? 8/20/2017
Firefox 8/20/2017
Google Chrome 8/20/2017
Google Chrome 8/20/2017
Google Chrome 8/20/2017
Opera 8/20/2017
Internet Explorer 8/20/2017
Internet Explorer 8/20/2017
如果我这样计算:
SELECT
COUNT (BrowserName) AS [Count Of Uses],
BrowserName AS [Browser],
Date
FROM
BROWSERS
GROUP BY
Date, BrowserName
我得到的结果是这样的:
Count Of Uses Browser Date
--------------------------------------------------
1 Firefox? 8/20/2017
1 Firefox 8/20/2017
3 Google Chrome 8/20/2017
2 Internet Explorer 8/20/2017
1 Opera 8/20/2017
问题请注意Firefox
(Firefox
和Firefox?
有两个条目。如何将这些组合成Firefox
的一个计数,以便我的最终结果如下:
Count Of Uses Browser Date
--------------------------------------------------
2 Firefox 8/20/2017
3 Google Chrome 8/20/2017
2 Internet Explorer 8/20/2017
1 Opera 8/20/2017
感谢。
答案 0 :(得分:2)
您可以使用case
:
SELECT Date,
(CASE WHEN BrowserName LIKE 'Firefox%' THEN 'Firefox'
ELSE BrowserName
END) as Browser,
COUNT(*) AS [Count Of Uses]
FROM BROWSERS
GROUP BY Date,
(CASE WHEN BrowserName LIKE 'Firefox%' THEN 'Firefox'
ELSE BrowserName
END) ;
答案 1 :(得分:2)
如果您只需要处理这种特殊情况:
SELECT
COUNT (*) AS [Count Of Uses],
replace(BrowserName, 'FireFox?', 'Firefox') AS [Browser],
Date
FROM BROWSERS
GROUP BY 2,3
如果您有多个类似的变体,请嵌套replace()
来电话:
replace(replace(BrowserName, 'FireFox?', 'Firefox'), 'Internet Exploder', 'Internet Explorer') AS [Browser]
答案 2 :(得分:1)
如果需要处理?一般来说
declare @T table (browser varchar(40), dt date);
insert into @T values
('Firefox?', '8/20/2017')
, ('Firefox', '8/20/2017')
, ('Google Chrome', '8/20/2017')
, ('Google Chrome', '8/20/2017')
, ('Google Chrome?', '8/20/2017')
, ('Opera', '8/20/2017')
, ('Internet Explorer', '8/20/2017')
, ('Internet Explorer',' 8/20/2017')
, ('Internet Explorer', '8/21/2017')
, ('Internet Explorer',' 8/21/2017');
with cte as
( select t.dt, t.browser
, SUBSTRING(REVERSE(t.browser),1,1) as f
, case when SUBSTRING(reverse(t.browser), 1, 1) = '?' then substring(t.browser, 1, LEN(t.browser ) -1) else t.browser end as browserT
from @T t
)
select cte.dt as [date], cte.browserT as browswer, count(*) as [count]
from cte
group by cte.dt, cte.browserT
order by cte.dt, cte.browserT;