是否可以将行与相关数据组合在一起,下面的示例将使其清楚。我正在使用这个脚本:
SELECT AlertName, COUNT(AlertName) as NumAlerts
FROM Alerts
GROUP BY AlertName
ORDER BY AlertName
结果是:
AlertName NumAlets
------------------------|---------------
...
Windows Services SQL 9
...
Windows Services - Core 7
Windows Services Core 271
Windows Services: Core 90
...
但是我想组合(分组)这些行并总结NumAlets以获得此结果:
AlertName NumAlets
------------------------|---------------
...
Windows Services SQL 9
Windows Services (Core) 368
...
我该怎么做?
提前谢谢!
答案 0 :(得分:4)
你需要一张表来将各种拼写翻译成一个:
DECLARE @Translation TABLE (
AlertName varchar(100),
CommonAlertName varchar(100)
)
INSERT INTO @Translation (AlertName, CommonAlertName)
VALUES ('Windows Services SQL', 'Windows Services SQL'),
('Windows Services - Core', 'Windows Services (Core)'),
('Windows Services Core', 'Windows Services (Core)'),
('Windows Services: Core', 'Windows Services (Core)')
SELECT T.CommonAlertName, SUM(A.NumAlerts) AS NumAlerts
FROM Alerts A
INNER JOIN @Translation T ON A.AlertName = T.AlertName
GROUP BY T.CommonAlertName
答案 1 :(得分:1)
Zoff的答案是合理的,但逻辑应该是left join
,因此翻译表中不必存在翻译:
with translation as (
select 'Windows Services SQL' as AlertName, 'Windows Services SQL' as CommonAlertName union ll
select 'Windows Services - Core', 'Windows Services (Core)' union all
select 'Windows Services Core', 'Windows Services (Core)' union all
select 'Windows Services: Core', 'Windows Services (Core)'
)
SELECT COALESCE(T.CommonAlertName, A.AlertName), SUM(A.NumAlerts) AS NumAlerts
FROM Alerts A LEFT JOIN
Translation T
ON A.AlertName = T.AlertName
GROUP BY COALESCE(T.CommonAlertName, A.AlertName);
答案 2 :(得分:1)
你也可以通过一个过滤掉所有非字母数字字符的函数来实现这一点,这样就可以像" Windows服务 - 核心"和#34; Windows服务(核心)"两者都成为" WindowsServicesCore"并相互匹配。
CREATE FUNCTION dbo.UDF_ParseAlphaChars
(
@string VARCHAR(8000)
)
RETURNS VARCHAR(8000)
AS
BEGIN
DECLARE @IncorrectCharLoc SMALLINT
SET @IncorrectCharLoc = PATINDEX('%[^0-9A-Za-z]%', @string)
WHILE @IncorrectCharLoc > 0
BEGIN
SET @string = STUFF(@string, @IncorrectCharLoc, 1, '')
SET @IncorrectCharLoc = PATINDEX('%[^0-9A-Za-z]%', @string)
END
SET @string = @string
RETURN @string
END
,查询如下所示。
select min(AlertName) as AlertName, COUNT(*) as NumAlerts
from Alerts
group by dbo.UDF_ParseAlphaChars( AlertName)
答案 3 :(得分:0)
SELECT rs.AlertName, COUNT(1) Totals
FROM (
SELECT CASE
WHEN AlertName LIKE 'Windows Services%Core'
THEN 'Windows Services (Core)'
WHEN AlertName LIKE 'Windows Services%SQL'
THEN 'Windows Services (SQL)'
ELSE AlertName END AlertName
from ALERTS) RS
Group By rs.AlertName