简体   繁体   中英

sql query with grouped by column

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

Is this what you want?

select
    l.category,
    count(*) no_listing_transactions
    100.0 * count(*) / sum(count(*)) over() per100
from t
inner join l on l.listing_id = t.listing_id
group by l.category

This gives you the count of transactions per category, and the percent that this count represents over the total number of transactions.

Note that this makes uses of window functions, which require MySQL 8.0. In earlier versions, one solution would be to would use a correlated subquery (assuming that there are no "orphan" transactions):

select
    l.category,
    count(*) no_listing_transactions
    100.0 * count(*) / (select count(*) from t) per100
from t
inner join l on l.listing_id = t.listing_id
group by l.category

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

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