【问题标题】:SQL : return all rows that contain particular value more than onceSQL:返回所有包含特定值的行不止一次
【发布时间】:2014-03-05 01:56:13
【问题描述】:

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

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)

我想以降序返回列 Qty 的出现,其值为“2”(出现了多少次)。

【问题讨论】:

  • 糟糕,删除“table”是一个错误,但差异显示我修改了很多其他的东西(数量等),而我没有。这是一个错误,还是没有记录的同时编辑?

标签: sql .net sql-server-2008


【解决方案1】:

您想要条件聚合(即使用带有聚合函数的case 语句):

select store, sum(case when Qty = '2' then 1 else 0 end) as Qty
from table t
group by store;

【讨论】:

  • 谢谢,就是这样。短而清晰
【解决方案2】:
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 的数量以降序显示商店。

【讨论】:

    猜你喜欢
    • 2022-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多