如何用sql server中的group by和where显示数据?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何用sql server中的group by和where显示数据?相关的知识,希望对你有一定的参考价值。
我用这个案例来显示数据跟随where
和group by
。以下是18/12/2017
的样本。
SELECT
PROID,
MAX(COUNT_NUMBER) AS COUNT_NUMBER_OLD,
CONVERT(CHAR(10), DATETIME_INPUT, 101) AS PreDate
FROM
TABLE_A
WHERE
CONVERT(VARCHAR(2), DATETIME_INPUT, 108) BETWEEN '18' AND '23'
AND CONVERT(CHAR(10), DATETIME_INPUT, 103) = '18/12/2017'
GROUP BY
PROID, CONVERT(CHAR(10), DATETIME_INPUT, 101);
结果是:
PROID COUNT_NUMBER_OLD PreDate
-------------------------------------------
01 1063 12/18/2017
02 365 12/18/2017
03 845 12/18/2017
它工作正常,但我想显示数据,如果没有数据在where条件。例如:CONVERT(CHAR(10), DATETIME_INPUT, 103) = '17/12/2017'
:
PROID COUNT_NUMBER_OLD PreDate
------------------------------------------
01 0 12/17/2017
02 0 12/17/2017
03 0 12/17/2017
我试着用
(CASE
WHEN COUNT_NUMBER IS NULL
THEN 0
ELSE MAX(COUNT_NUMBER)
END) AS COUNT_NUMBER_OLD
但我得到这个错误:
“TABLE_A.COUNT_NUMBER”列在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。
答案
您可以使用子查询并获取每个组的max count_number,然后执行ISNULL操作。
SELECT X.PROID,
ISNULL(X.COUNT_NUMBER,0) AS COUNT_NUMBER_OLD,
X.PreDate
FROM
(SELECT PROID,
ROW_NUMBER() OVER (PARTITION BY PROID,CONVERT(CHAR(10), DATETIME_INPUT, 101) ORDER BY COUNT_NUMBER DESC) AS RN,
CONVERT(CHAR(10), DATETIME_INPUT, 101) AS PreDate,
COUNT_NUMBER
FROM TABLE_A
WHERE CONVERT(VARCHAR(2), DATETIME_INPUT, 108) BETWEEN '18' AND '23'
AND CONVERT(CHAR(10), DATETIME_INPUT, 103) = '18/12/2017' ) X
WHERE X.RN=1
另一答案
我觉得你的列可能有NULL值。
默认情况下,MAX和MIN函数在评估数据时不计算NULL。如果COUNT_NUMBER列包含NULL值,则MAX和MIN都将忽略该值。
试试这个解决方案
SELECT PROID,
MAX(COALESCE(COUNT_NUMBER,0)) AS COUNT_NUMBER_OLD,
CONVERT(CHAR(10), DATETIME_INPUT, 101) AS PreDate
FROM TABLE_A
WHERE CONVERT(VARCHAR(2), DATETIME_INPUT, 108) BETWEEN '18' AND '23'
AND CONVERT(CHAR(10), DATETIME_INPUT, 103) = '17/12/2017'
GROUP BY PROID,
CONVERT(CHAR(10), DATETIME_INPUT, 101);
以上是关于如何用sql server中的group by和where显示数据?的主要内容,如果未能解决你的问题,请参考以下文章
如何用 seaborn 绘制 pandas 三列(用 group by 计算)
ElasticsearchElasticsearch如何实现 SQL语句中 Group By 和 Limit 的功能