sql query with grouped by column

Chris90 :

I have two tables as transactions and listings

Table T as fields of 

order_date timestamp 
order_id   BIGINT
listing_id INT
price INT

Table L with fields of 

listing_id INT 
price INT
category varchar

If i want to get the sell ratio for each category if sell ratio is defined as the number of sold listings divided by the total number of listings * 100, how can I compose this? would a case statement or cte work better?

listings table is for all listings available and transactions represents all sold

Thanks

gilbertdim :

Try this one

Schema (MySQL v5.7)


Query #1

Create Table `gilbertdim_333952_L` (
    listing_id int NOT NULL AUTO_INCREMENT,
    price float,
    category varchar(10),
    PRIMARY KEY (listing_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

There are no results to be displayed.


Query #2

INSERT INTO gilbertdim_333952_L (price, category) VALUES
(100, 'FOOD'),
(50, 'DRINKS');

There are no results to be displayed.


Query #3

Create Table `gilbertdim_333952_T` (
    order_id int NOT NULL AUTO_INCREMENT,
    order_date timestamp NULL DEFAULT CURRENT_TIMESTAMP,
    listing_id int,
    price float,
    PRIMARY KEY (order_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

There are no results to be displayed.


Query #4

INSERT INTO gilbertdim_333952_T (listing_id, price) VALUES
(1, 100),(1, 100),(1, 100),
(2, 50),(2, 50);

There are no results to be displayed.


Query #5

SELECT l.*, (COUNT(1) / (SELECT COUNT(1) FROM gilbertdim_333952_T) * 100) as sales
FROM gilbertdim_333952_L l
LEFT JOIN gilbertdim_333952_T t ON l.listing_id = t.listing_id
GROUP BY l.listing_id;
| listing_id | price | category | sales |
| ---------- | ----- | -------- | ----- |
| 1          | 100   | FOOD     | 60    |
| 2          | 50    | DRINKS   | 40    |

View on DB Fiddle

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=195002&siteId=1