我有一张Dog
表。每只狗都有Breed
,可以有0到2张照片。我需要收到每个品种的所有狗的照片数量:BreedId
和匹配PhotosCount
的表格。所以结果表应该是:
BreedID|PhotosCount
-------------------
1 |3
-------------------
2 |1
-------------------
答案 0 :(得分:5)
这应该可以解决问题:
COUNT
NULL
聚合函数根本不考虑BreedID
值。如果Photo1
或Photo2
的特定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;