SQL Query查询匹配列和计数行

时间:2016-05-03 16:15:00

标签: sql sql-server

我有一个SQL结果,它返回列中存在某些数据的每一行的计数。我想分组结果,其中分组值存在于表中的两列(P1和P2)中,当P1为NULL时,我想使用P2。

例如,我有一个初始查询结果如下:

+------+------+----------+
|  P1  |  P2  | SomeData |
+------+------+----------+
| Bob  | Mark | data     |
| NULL | Bob  | data     |
| Mark | Tony | data     |
| Mark | Sam  | data     |
| Mark | Bill | data     |
+------+------+----------+

我想修改此查询以进行分组,这样当P1为NULL时,新列将返回P2中的值。预期结果如下所示:

+------+-------+
|  P   | Counts|
+------+-------+
| Bob  |   2   |
| Mark |   3   |
+------+-------+

预期的查询看起来像这样,当然,我不能GROUP BY一个别名列:

SELECT
    (CASE WHEN P1 IS NOT NULL THEN P1 ELSE P2 END) AS P,
    COUNT(CASE WHEN SomeData IS NOT NULL THEN 1 ELSE 0 END) AS Counts
    FROM MyTable
    GROUP BY P

1 个答案:

答案 0 :(得分:2)

您正在寻找此

SELECT
CASE WHEN P1 IS NOT NULL THEN P1 ELSE P2 END AS P,
COUNT(SomeData) AS Counts
FROM MyTable
GROUP BY CASE WHEN P1 IS NOT NULL THEN P1 ELSE P2 END

或案例可以通过Coalesce/Isnull函数

进行简化
SELECT
COALESCE(P1,P2) AS P,
COUNT(SomeData) AS Counts
FROM MyTable
GROUP BY COALESCE(P1,P2)
  1. 只需使用整个CASE语句,而不是alias
  2. 无需Case语句count Not NULL Count(Colname)个值。 Not NULL聚合仅计算private