SQL Server 2008 - 如何将行与相关数据合并

SQL Sever 2008 - How to combine rows with related data

是否可以将行与相关数据结合起来,下面的例子会很清楚。我正在使用这个脚本:

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  
...

我该怎么做?

提前致谢!

您需要 table 才能将各种拼写合二为一:

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

Zoff 的回答是合理的,但逻辑应该是 left join 所以翻译中不一定存在翻译 table:

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);

您还可以使用过滤掉所有非字母数字字符的函数来完成此操作,以便 "Windows Services - Core" 和 "Windows Services (Core)" 等字符串都变成 "WindowsServicesCore" 并相互匹配。

以下函数来自http://blog.sqlauthority.com/2007/05/13/sql-server-udf-function-to-parse-alphanumeric-characters-from-string/

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)
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