[英]sql query with grouped by column
我有兩個表作為交易和列表
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
如果我想獲得每個類別的銷售比率,如果銷售比率定義為已銷售列表的數量除以列表總數 * 100,我該如何組合? case 語句或 cte 會更好嗎?
列表表用於所有可用列表,交易代表所有已售出
謝謝
這是你想要的嗎?
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
這為您提供了每個類別的交易計數,以及該計數占交易總數的百分比。
請注意,這使用了需要 MySQL 8.0 的窗口函數。 在早期版本中,一種解決方案是使用相關子查詢(假設沒有“孤立”事務):
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
試試這個
架構 (MySQL v5.7)
查詢#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;
沒有要顯示的結果。
查詢#2
INSERT INTO gilbertdim_333952_L (price, category) VALUES
(100, 'FOOD'),
(50, 'DRINKS');
沒有要顯示的結果。
查詢 #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;
沒有要顯示的結果。
查詢 #4
INSERT INTO gilbertdim_333952_T (listing_id, price) VALUES
(1, 100),(1, 100),(1, 100),
(2, 50),(2, 50);
沒有要顯示的結果。
查詢 #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 |
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.