SQL GROUP BY返回单行

时间:2018-01-19 20:42:51

标签: sql sql-server group-by

我有以下SQL来获取我需要的实际数据,但是我希望每个“Area”有一行,其中列数为NULL,False和True。我可以添加什么来使SQL语句看起来像这样?

NullCount     FalseCount     TureCount     AreaName      AreaID
8              4             3             Capital Metro  1 
0              0             1             Great Lakes    3
9              4             6             Pacific        6

当前SQL:

SELECT 
    tblRecyclingStatusRequests.ReturnUSM
    ,tblAreas.AreaID
    ,tblAreas.AreaName
    ,COUNT(ISNULL(tblRecyclingStatusRequests.ReturnUSM, 0)) AS CountOf
FROM            
    tblRecyclingStatusRequests INNER JOIN
    tblFacilities ON tblRecyclingStatusRequests.FacilityID =tblFacilities.FacilityID INNER JOIN
    tblDistricts ON tblFacilities.DistrictID = tblDistricts.DistrictID INNER JOIN
    tblAreas ON tblDistricts.AreaID = tblAreas.AreaID
GROUP BY tblRecyclingStatusRequests.ReturnUSM, tblAreas.AreaID, tblAreas.AreaNameCurrent

当前结果:

ReturnUSM   AreaID  AreaName        CountOf
NULL        1       Capital Metro   8
0           1       Capital Metro   3
1           1       Capital Metro   4
1           3       Great Lakes     1
NULL        6       Pacific         9
0           6       Pacific         4
1           6       Pacific         6

2 个答案:

答案 0 :(得分:2)

条件聚合是一种方法:

SELECT MAX(CASE WHEN ReturnUSM IS NULL THEN CountOf ELSE 0 END) NullCount,
       MAX(CASE WHEN ReturnUSM = 0 THEN CountOf ELSE 0 END) FalseCount,
       MAX(CASE WHEN ReturnUSM = 1 THEN CountOf ELSE 0 END) TrueCount,
       AreaName,
       AreaID
FROM (YourCurrentQuery) a
GROUP BY AreaName,
         AreaID

条件SUM()看起来也会起作用:

SELECT SUM(CASE WHEN RSR.ReturnUSM IS NULL THEN 1 ELSE 0 END) NullCount,
       SUM(CASE WHEN RSR.ReturnUSM = 0 THEN 1 ELSE 0 END) FalseCount,
       SUM(CASE WHEN RSR.ReturnUSM = 1 THEN 1 ELSE 0 END) TrueCount,
       A.AreaName,
       A.AreaID
FROM tblRecyclingStatusRequests RSR
INNER JOIN tblFacilities F ON RSR.FacilityID = F.FacilityID 
INNER JOIN tblDistricts D ON F.DistrictID = D.DistrictID 
INNER JOIN tblAreas A ON D.AreaID = A.AreaID
GROUP BY A.AreaID, A.AreaName

答案 1 :(得分:2)

您可以使用案例陈述进行条件计数:

SELECT 
  count(case when tblRecyclingStatusRequests.ReturnUSM is null then 1 else null end) NullCount
  ,count(case when tblRecyclingStatusRequests.ReturnUSM=0 then 1 else null end) FalseCount
  ,count(case when tblRecyclingStatusRequests.ReturnUSM=1 then 1 else null end) TrueCount
  ,tblAreas.AreaID
  ,tblAreas.AreaName
  ,COUNT(ISNULL(tblRecyclingStatusRequests.ReturnUSM, 0)) AS CountOf
FROM            
  tblRecyclingStatusRequests INNER JOIN
  tblFacilities ON tblRecyclingStatusRequests.FacilityID =tblFacilities.FacilityID INNER JOIN
  tblDistricts ON tblFacilities.DistrictID = tblDistricts.DistrictID     
INNER JOIN
  tblAreas ON tblDistricts.AreaID = tblAreas.AreaID
GROUP BY tblAreas.AreaID,   tblAreas.AreaNameCurrent