GROUP BY子句中的SQL表达式或列

时间:2015-04-17 09:12:04

标签: sql group-by

这更像是理论问题而不是问题。假设我有一个包含三列id, Country1, Country2的表格。

我想运行简单的示例查询:

SELECT 
     CASE WHEN Country1 = '' THEN Country2 ELSE Country1 END AS [Country], 
     COUNT(id) AS [Countries_count]
FROM ExampleTable
GROUP BY 
     CASE WHEN Country1 = '' THEN Country2 ELSE Country1 END

无论我将整个非聚合表达式

,我的查询都会有效
GROUP BY 
     CASE WHEN Country1 = '' THEN Country2 ELSE Country1 END

或仅包含此表达式中的列

GROUP BY 
     Country1,
     Country2

GROUP BY子句中。

我是否应该将GROUP BY子句放入每个非聚合表达式(有时真的很大)或者我只能放置这些表达式中的列?如果我能/不能,为什么?

1 个答案:

答案 0 :(得分:2)

您在询问哪个更适合查询:

GROUP BY CASE WHEN Country1 = '' THEN Country2 ELSE Country1 END

GROUP BY Country1, Country2

答案通常是第一个。但是,这取决于你想做什么。

考虑以下数据:

ID       Country1       Country2
 1                             A
 2              A              A
 3              A

此查询:

SELECT (CASE WHEN Country1 = '' THEN Country2 ELSE Country1 END) AS [Country], 
       COUNT(id) AS [Countries_count]
FROM ExampleTable
GROUP BY (CASE WHEN Country1 = '' THEN Country2 ELSE Country1 END)

返回一行总计数

A    3

此版本

SELECT (CASE WHEN Country1 = '' THEN Country2 ELSE Country1 END) AS [Country], 
       COUNT(id) AS [Countries_count]
FROM ExampleTable
GROUP BY Country1, Country2

返回三行:

A    1
A    1
A    1

在大多数情况下,我想要一行计数为3.在某些情况下,这可能是所需的输出。