SQL中的多重计数查询返回什么?

时间:2016-04-20 09:25:28

标签: sql sqlite

我有一个product表,每个产品可能都是deliveredidleshippingpreparing

我想显示一个列表,其中包含每个州的产品数量,我可以在这里查看如何查询:

How to get multiple counts with one SQL query?

但是,此查询返回了什么,以及如何将返回值分配给4个整数,称为deliveredCountidleCountshippingCountpreparingCount

PS:为了记录,我在Android中使用带有JAVA的OrmLite的SQLite

编辑:在这个问题中,人们解释当你想获得多个计数时要执行什么查询,但他们没有告诉我们该查询返回什么以及采用何种格式。例如:

SELECT a.distributor_id,
    (SELECT COUNT(*) FROM myTable WHERE level='personal' and distributor_id = a.distributor_id) as PersonalCount,
    (SELECT COUNT(*) FROM myTable WHERE level='exec' and distributor_id = a.distributor_id) as ExecCount,
    (SELECT COUNT(*) FROM myTable WHERE distributor_id = a.distributor_id) as TotalCount
FROM myTable a ;

这个的返回类型是什么?格式是什么?

PS2:由于缺乏足够的信息,有人很快就向我提出了问题。然后我编辑了它,但是downvote仍然存在:(

3 个答案:

答案 0 :(得分:2)

很难肯定地说,但听起来你需要在你提供的链接中使用最佳答案的版本。

喜欢的东西;

SELECT ProductID,
    COUNT(*) AS Total,
    SUM(CASE WHEN pStatus = 'delivered' THEN 1 ELSE 0 END) DeliveredCount,
    SUM(CASE WHEN pStatus = 'idle' THEN 1 ELSE 0 END) IdleCount,
    SUM(CASE WHEN pStatus = 'shipping' THEN 1 ELSE 0 END) ShippingCount,
    SUM(CASE WHEN pStatus = 'preparing' THEN 1 ELSE 0 END) PreparingCount
FROM ProductTable
GROUP BY ProductID

这将返回类似的内容;

ProductID | DeliveredCount | IdleCount | ...
1         | 250            | 3250      | ...

答案 1 :(得分:2)

您可能想尝试一下。

SELECT
SUM(CASE WHEN Prod = 'delivered' THEN 1 ELSE 0 END) as deliveredCount,
SUM(CASE WHEN Prod = 'idle' THEN 1 ELSE 0 END) as idleCount,
SUM(CASE WHEN Prod = 'shipping' THEN 1 ELSE 0 END) as shippingCount,
SUM(CASE WHEN Prod = 'preparing' THEN 1 ELSE 0 END) as preparingCount
FROM Product

答案 2 :(得分:1)

select
  concat(state, "Count"),
  count(*)
from product
group by state

哪个会返回4行(假设有四个唯一的状态值):

fooCount | 15
etc