sql – 如果value为空,则组合行

前端之家收集整理的这篇文章主要介绍了sql – 如果value为空,则组合行前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用sql-Server 2008.我需要组合具有相同名称的行并在以下情况下增加计数器:

> 1或更多相同名称的Id为空白
>如果Id为NULL,则不合并行!
>如果具有相同的名称但不同的ID,则不合并行

目前输出

Name    Id   Cnt
John    1     1
Peter   2     2 -- This Peter with the same Id have 2 entries so Cnt = 2
Peter   3     1 -- This is other Peter with 1 entry so Cnt = 1
Lisa    4     1
Lisa   NULL   1
David   5     1
David         1 -- here Id is blank ''
Ralph         2 -- Ralph have both rows with blank Id so Cnt = 2

期望的输出

Name    Id   Cnt
John    1     1
Peter   2     2
Peter   3     1
Lisa    4     1
Lisa   NULL   1 -- null still here
David   5     2 -- merged with blank '' so Cnt = 2
Ralph         2 -- merged both blanks '' so Cnt = 2

SQL查询

这是我现在使用的示例查询

SELECT Name,Id,COUNT(Id) AS Cnt
FROM Employees                       
WHERE Condition = 1                 
GROUP BY Name,Id

我试过的:

在SELECT子句中将聚合MAX添加到Id并仅按名称分组,但在这种情况下,合并的行具有NULL值并且具有相同的名称,具有不同的Id,这对我来说是错误的.

SELECT Name,MAX(Id),-- added aggregate
       COUNT(Id) AS Cnt
FROM Employees                       
WHERE Condition = 1                 
GROUP BY Name -- grouped by Name only

你有什么想法吗?如果对问题一无所知 – 请问我,我会提供更多细节.

更新:

DDL

CREATE TABLE Employees
(
  Name NVARCHAR(40),Id NVARCHAR(40)
);

DML

INSERT INTO Employees VALUES
 ('John','1'),('Peter','2'),'3'),('Lisa','4'),NULL),('David','5'),''),('Ralph','')

演示:SQL FIDDLE

解决方法

编辑
DECLARE @Data table (Name varchar(10),Id varchar(10)) -- Id must be varchar for blank value
INSERT @Data VALUES
('John',--('Peter',--For test
('Lisa','')
SELECT 
    Name,COUNT(*) + ISNULL(
        (SELECT COUNT(*) FROM @data WHERE Name = d.Name AND Id = '' AND d.Id <> ''),0) AS Cnt 
FROM @data d 
WHERE 
    Id IS NULL 
    OR Id <> '' 
    OR NOT EXISTS(SELECT * FROM @data WHERE Name = d.Name AND Id <> '')
GROUP BY Name,Id
原文链接:https://www.f2er.com/mssql/78137.html

猜你在找的MsSQL相关文章