Leetcode SQL 50 -- 1484. Group Sold Products By The Date

  1. Question
    1. Table name: Activities
  2. Explaination
    1. Type of Items
    2. GROUP_CONCAT(): Rolling up multiple rows in single row
  3. Solution

Question

Table name: Activities

Column Name Type
sell_date date
product varchar

Each row of this table contains the product name and the date it was sold in a market.

Write a solution to find for each date the number of different products sold and their names.
The sold products names for each date should be sorted lexicographically.
Return the result table ordered by sell_date.

Explaination

Again, there are two tasks we need to solve:

  1. Count how many types of products are sold in one day
  2. List all types of items into a single column

Type of Items

We can simply count how many products are sold using COUNT, groupped by the date they belong to:

SELECT COUNT(*) AS num_sold, 
FROM Activities
GROUP BY sell_date

However, if a product is sold twice in one day, they will be counted twice as well.
Since the question asked for the number of different products sold,
we need to specify the column we are counting, and use the keyword DINSTINCT to remove duplicates:

SELECT COUNT(DISTINCT product) AS num_sold, 
FROM Activities
GROUP BY sell_date

GROUP_CONCAT(): Rolling up multiple rows in single row

To roll data from multiple rows in single row, we may use the GROUP_CONCAT() function,
and below is the syntax:

GROUP_CONCAT(expr 
  [ORDER BY {unsigned_integer | col_name | expr} ASC | DESC]
    [SEPARATOR str_val]
)
  • It can be sorted with respect to other column by using ORDER BY inside the function
  • You may define custom string as the separator of the output (default is comma)

Solution

SELECT sell_date, COUNT(DISTINCT product) AS num_sold, 
    GROUP_CONCAT(DISTINCT product) AS products
FROM Activities
GROUP BY sell_date

More SQL 50 questions: here


Please cite the source for reprints, feel free to verify the sources cited in the article, and point out any errors or lack of clarity of expression. You can comment in the comments section below or email to GreenMeeple@yahoo.com
This Repo