过滤掉HAVING子句中的字段组合

时间:2017-05-02 23:20:45

标签: sql sql-server sql-server-2012 group-by having

我知道这可能是非常基本的,但我认为它会更快。

    +----------+----------+---------+
    | PersonID | No Shows | Cancels |
    +----------+----------+---------+
    |        1 |        2 |       0 |
    |        1 |        5 |       1 |
    |        1 |        0 |       0 |
    |        2 |        0 |       0 |
    |        2 |        0 |       0 |
    |        3 |        1 |       0 |
    |        3 |        0 |       0 |
    |        4 |        1 |       1 |
    |        4 |        3 |       2 |
    |        4 |        0 |       0 |
    +----------+----------+---------+

我试图消除那些将NoShows和Cancels的总和组合为0的人。例如:PersonID=2

尝试:

SELECT
    PersonID
    ,SUM(NoShows) AS TotalNS
    ,SUM(Cancels) AS TotalCanc

FROM Table1
GROUP BY PersonID
HAVING SUM(NoShows) > 0 AND SUM(Cancels) > 0

这显然不会起作用,因为如果NoShows或Cancels中的任何一个为0,它将开始移除人员。例如:PersonID=3

期望的输出:

+--------------+----------+---------+
|     PersonID | No Shows | Cancels |
+--------------+----------+---------+
|            1 |        7 |       1 |
|            3 |        1 |       0 |
|            4 |        4 |       3 |
+--------------+----------+---------+

2 个答案:

答案 0 :(得分:0)

尝试一下,如果您遇到任何困难,请告诉我。

SELECT
    PersonID
    ,SUM(NoShows) AS TotalNS
    ,SUM(Cancels) AS TotalCanc

FROM Table1
GROUP BY PersonID
HAVING SUM(NoShows) > 0 or SUM(Cancels) > 0

答案 1 :(得分:0)

你的问题是:

  

我试图只获得那些同时具有Total总和的组合   NoShows和Cancels为0.例如:PersonID = 2

答案是:

SELECT PersonID
FROM Table1
GROUP BY PersonID
HAVING SUM(NoShows) = 0 AND SUM(Cancels) = 0;

我不清楚为什么你会接受不同逻辑的答案。