user2727704
user2727704

Reputation: 645

SQL query to determine the column based on count of rows

Need help with writing a SQL query on a purchase table and changing the 'item' column to 'Multi' if multiple items were purchased on the same day:

Heres the sample table:

name | date       | item 
-------------------------
Jack | 20120105   |  TV
Jack | 20120105   |  Table
Jack | 20120105   |  Chair
Ryan | 20170822   |  TV
Roma | 20190525   |  TV
Bill | 20110121   |  Table

Jack in the above table for example has multiple purchases on same day so would like to result to be 'Multi' for 'item' column:

name | date       | item 
-------------------------
Jack | 20120105   |  Multi
Ryan | 20170822   |  TV
Roma | 20190525   |  TV
Bill | 20110121   |  Table

This query works but what if there are more than 2 items purchased by same person on same day:

select name
       case when p1.item <> p2.item then 'U'
             else p1.item
             end as item_name
from purchases p1 join purchases p2 on (p1.name = p2.name)

Any other better ways to achieve this?

Thanks!

Upvotes: 0

Views: 39

Answers (2)

Nick
Nick

Reputation: 147166

You can use an EXISTS clause with SELECT DISTINCT to change the item to Multi when more than one item is purchased on the same day:

SELECT DISTINCT name, date,
       CASE WHEN EXISTS (SELECT *
                         FROM purchases p2 
                         WHERE p2.name  = p1.name
                           AND p2.date  = p1.date
                           AND p2.item != p1.item) THEN 'Multi'
            ELSE item 
        END AS item
FROM purchases p1

Another alternative would be to aggregate and check the COUNT of items bought by a person on a given day:

SELECT name, date, 
       CASE WHEN COUNT(*) > 1 THEN 'Multi'
            ELSE MIN(item)
       END AS item
FROM purchases
GROUP BY name, date

In both cases the output is:

name    date        item
Jack    20120105    Multi
Ryan    20170822    TV
Roma    20190525    TV
Bill    20110121    Table

Demo on SQLFiddle

Upvotes: 0

Gordon Linoff
Gordon Linoff

Reputation: 1269873

Use aggregation and a case expression:

select name, date,
       (case when min(item) = max(item) then min(item)
             else 'Multi'
        end) as item_name
from purchases
group by name, date;

Upvotes: 2

Related Questions