在sql中的count内应用where子句

时间:2014-10-07 18:57:39

标签: sql

SELECT 
    Rooms.Building, 
    Count(Rooms.Room) AS TotalApartments, 
    Count(Rooms.Room) AS ApartmentsOccupied
FROM 
    Rooms
WHERE 
    (((Rooms.AssetType) <> 'LC')) 
GROUP BY 
    Rooms.Building;

我想计算Rooms.Room Rooms.Occupied = TrueApartmentsOccupied),但是当我将此子句放入我的sql时,它也会将whereA应用于TotalApartments列

2 个答案:

答案 0 :(得分:1)

您可以将一些逻辑移动到CASE语句中以进行条件摘要:

SELECT
    Rooms.Building,
    Count(Rooms.Room) AS TotalApartments,
    Sum(CASE WHEN Rooms.Occupied = True THEN 1 ELSE 0 END) AS ApartmentsOccupied
FROM 
    Rooms
WHERE 
    (((Rooms.AssetType) <> 'LC')) 
GROUP BY 
    Rooms.Building;

我不确定我的头脑,但您可能还需要将该计数更改为SUM:

Sum(1) AS TotalApartments

另外,在一些sql方言中,'True'值为1,所以你可以为这个占用的数量得到这样的东西:

Sum(Rooms.Occupied) AS ApartmentsOccupied

答案 1 :(得分:0)

你可以这样做

SELECT 
    Building, 
    Count(Room) AS TotalApartments, 
    SUM(CASE WHEN Occupied = True THEN 1 ELSE 0 END) AS ApartmentsOccupied
FROM 
    Rooms
WHERE 
    AssetType <> 'LC' 
GROUP BY 
    Building;