3

I have a product table and every product might be delivered, idle, shipping, preparing.

I want to show a list with the counts of products for each state, and I can see how to query for that here:

How to get multiple counts with one SQL query?

However, what does this query return, and how do I assign the return value to lets say, 4 integers, called deliveredCount, idleCount, shippingCount, preparingCount?

PS: For the record, I am using SQLite with OrmLite in Android with JAVA

EDIT: In this SO question people explain what Query to do when you want to get multiple counts, but they don't tell us what does that query return and in what format. For example:

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 ;

What is the return type of this and what is the format?

PS2: Someone was really quick to downvote my question because it lacked sufficient information. Then I edited it, but the downvote still remains :(

Community
  • 1
  • 1
Kaloyan Roussev
  • 14,515
  • 21
  • 98
  • 180

3 Answers3

5

Hard to say for sure but sounds like you need to use a version of the top answer in the link you have provided.

Something like;

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

This will return something like;

ProductID | DeliveredCount | IdleCount | ...
1         | 250            | 3250      | ...
William
  • 6,332
  • 8
  • 38
  • 57
2

You might want to try this.

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
1
select
  concat(state, "Count"),
  count(*)
from product
group by state

Which would return 4 rows (assuming four unique values of state):

fooCount | 15
etc
Jordan McQueen
  • 777
  • 5
  • 10