简体   繁体   中英

Count distinct attribute values based on two other columns in SQL

I've got a table with three key attributes, like below:

输入表

I want to query it to figure out the number of items sold based on item type and date sold. So the output might look something like this:

http://i.stack.imgur.com/27glz.png

My query looks like this:

SELECT SaleItem AS 'Item Sold', SaleDay AS 'Item Sell Day', COUNT(DISTINCT SaleNumber) AS 'Number'
FROM Sales
GROUP BY SaleDay, SaleItem

This is returning a table with the SaleItems organized properly, but the count is the total number sold, excluding the SaleDay attribute.

It's returning the total number of sales per item instead of only the sales on that day per item. So, if 7 pens were sold Monday and 6 on Tuesday it should return two tuples (7, Monday, Pen) and (6, Tuesday, pen). Currently, its returning (13, Monday, pen) and (13, Tuesday, pen).

How can I fix this query?

You complecated your question, by next simply show the input & output so you will get answer faster, any way, here is your solution: you don't need the distinct

SELECT SaleItem AS 'Item Sold', 
       SaleDay AS 'Item Sell Day', 
       COUNT(SaleItem) AS 'Number'
FROM Sales
GROUP BY SaleDay, SaleItem

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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