简体   繁体   中英

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!

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;

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

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