繁体   English   中英

SQL:返回包含特定值的所有行不止一次

[英]SQL : return all rows that contain particular value more than once

我有一个包含以下内容的表:

store        Qty
----
store1       1
store2       2
store1       3
store2       2

我想输出这个:

------------
store     Qty
store2    2(value '2' occurs 2 times)
store1    0(value '2' occurs 0 times)

我想按降序返回值“ 2”(发生了多少次)的列Qty出现。

您需要条件聚合(即,将case语句与聚合函数一起使用):

select store, sum(case when Qty = '2' then 1 else 0 end) as Qty
from table t
group by store;
SELECT t.store, COUNT(QTY) AS QTY2
FROM TABLE T
WHERE t.QTY = 2
GROUP BY t.store
ORDER BY COUNT(QTY) DESC

这应该工作。 它将提供按商店分组的2个存货的计数,并根据2个存货的数量按降序显示商店。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM