来自不同列的SQL计数值

时间:2016-10-03 11:48:15

标签: sql sql-server tsql

我有一张Dog表。每只狗都有Breed,可以有0到2张照片。我需要收到每个品种的所有狗的照片数量:BreedId和匹配PhotosCount的表格。所以结果表应该是:

BreedID|PhotosCount
-------------------
1      |3
-------------------
2      |1
-------------------

Dogs

4 个答案:

答案 0 :(得分:5)

这应该可以解决问题:

COUNT

NULL聚合函数根本不考虑BreedID值。如果Photo1Photo2的特定NULL所有值均为COUNT,则0会返回{{1} }}

答案 1 :(得分:1)

这应该在单次扫描中起作用:

SELECT
    BreedID,
    SUM(CASE WHEN Photo1 IS NOT NULL THEN 1 ELSE 0 END)
    + SUM(CASE WHEN Photo2 IS NOT NULL THEN 1 ELSE 0 END) [Count]
FROM Table
GROUP BY BreedID

答案 2 :(得分:1)

使用Photo1和Photo2的分组依据 SUM

注意:如果您想要每只狗的输出,您必须在组子句中包含DogId。

;WITH T AS
(
    SELECT          
        BreedId,
        SUM (CASE ISNULL(Photo1,0) WHEN 1 THEN 1 ELSE 0 END) AS Photo1,
        SUM (CASE ISNULL(Photo2,0) WHEN 1 THEN 1 ELSE 0 END) AS Photo2
    FROM TableName
    Group By BreedId
)
SELECT      
    BreedId,
    SUM(Photo1+Photo2) AS TotalPhoto
FROM T

或简单

SELECT        
    BreedId,
    SUM (CASE ISNULL(Photo1,0) WHEN 1 THEN 1 ELSE 0 END +  CASE ISNULL(Photo2,0) WHEN 1 THEN 1 ELSE 0 END) AS TotalPhoto       
FROM TableName
Group By BreedId

答案 3 :(得分:0)

SELECT BreedID AS Breed, COUNT(Photo1) + COUNT(Photo2) AS #ofPhotos
FROM Dog
GROUP BY BreedID;