简体   繁体   English

按列分组的sql查询

[英]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?如果我想获得每个类别的销售比率,如果销售比率定义为已销售列表的数量除以列表总数 * 100,我该如何组合? would a case statement or cte work better? case 语句或 cte 会更好吗?

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.请注意,这使用了需要 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)架构 (MySQL v5.7)


Query #1查询#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查询#2

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

There are no results to be displayed.没有要显示的结果。


Query #3查询 #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查询 #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查询 #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在 DB Fiddle 上查看

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM