在SQL Server中按ID查找计数组

时间:2019-01-03 12:44:58

标签: sql sql-server group-by count

我需要一些帮助来解决此查询。我有一张桌子,其中包含要在以下提到的房间里停留的乘客的年龄:

Age    RoomId 
-----    ---
 1        1
12        1
 8        1
19        1
3         2
12        2
18        2
21        3

此外,我有一个属性表,其中包含孩子的最大年龄和婴儿的最大年龄。根据乘客的年龄,我需要将他们分为成人,儿童和婴儿,以区分每个属性。

Properties表结构

Property Id Maximum_child_age  Maximum_infant_age
-------------------------------------------------
1                11                     2

所需的输出

RoomId  Adult Child Infant PropertyId
--------------------------------
 1       2       1      1      1
 2       2       1      0      1
 3       1       0      0      1

2 个答案:

答案 0 :(得分:3)

使用条件聚合:

SELECT 
    SUM(CASE WHEN pas.age > ppt.Maximum_child_age THEN 1 ELSE 0 END) AS Adult,
    SUM(CASE WHEN pas.age BETWEEN Maximum_infant_age AND ppt.Maximum_child_age THEN 1 ELSE 0 END) AS Child,
    SUM(CASE WHEN pas.age < ppt.Maximum_infant_age THEN 1 ELSE 0 END) AS Infant,
    ppt.id
FROM 
    passengers pas
    CROSS JOIN properties ppt
GROUP BY ppt.id

答案 1 :(得分:1)

交叉连接属性,然后进行条件聚合。

SELECT count(CASE
               WHEN pa.ages > pr.maximum_child_age THEN
                 1
             END) adult,
       count(CASE
               WHEN pa.ages > pr.maximum_infant_age
                    AND pa.ages <= pr.maximum_child_age THEN
                 1
             END) child,
       count(CASE
               WHEN pa.ages <= pr.maximum_infant_age THEN
                 1
             END) infant,
       pr.propertyid
       FROM passengers pa
            CROSS JOIN properties pr
       GROUP BY pr.propertyid;