Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL count number of groups

I have a table with pallets, items, item quantity:

pallet | item | qty
-------------------
  1        1     2
  1        2     4
  2        3     2
  2        5     3
  3        4     4

I need to find count(pallet), count(item), sum(qty)

count(pallets) | count(items) | sum(qty)
----------------------------------------
      3                5           15

I can get the sum(qty) and count(item) with

select count(0) as totalItems, sum(qty) as total from table

Is there a way to get the number of pallets without a sub-query?

like image 678
Tony Brix Avatar asked May 14 '15 22:05

Tony Brix


1 Answers

Yes, use DISTINCT

select count(distinct pallet) as pallets,
       sum(qty) as total, 
       count(*) as totalItems 
from your_table
like image 79
juergen d Avatar answered Oct 04 '22 02:10

juergen d