查找每次活动的总销量、每次活动中每种产品的总销量以及活动持续时间(以天为单位)。
用一条 SQL 语句完成这个
这是我到目前为止所拥有的,这只是最低限度的。我认为涉及某种子查询,但我不确定。
**1。在每个事件中选择总单位:
SELECT DISTINCT(units), count(*)
from (JOIN TABLE i and TABLE e on Event_ID --> I know how to do this, just shortening the code)
GROUP BY event_id
**
**2。每次活动销售的每种产品的总单位
SELECT COUNT(UNITS)/COUNT(PROUDCT) AS 'Units Per Product Sold'
FROM inventory
GROUP BY event_id**
我的主要问题是将子句组合在一起并实现子查询(如果确实需要)和第二个 select 语句的确切措辞
答案 0 :(得分:0)
你可以使用windows函数来实现:
架构
create table event(event_id int ,event_name varchar(20),event_start_date date,event_end_date date);
insert into event values(1,'a','2021/03/05','2021/03/06');
create table event_inventory_table(event_id int, product_id int,units int);
insert into event_inventory_table values(1,1,10);
insert into event_inventory_table values(1,5,5);
查询 #1 (SQL Server)
select e.event_id,e.event_name,datediff(day,e.event_start_date,e.event_end_date)evnt_Duration,product_id,sum(units)over(partition by e.event_id) Units_Sold,sum(units)over(partition by e.event_id,product_id) units_sold_per_product from event e
在 e.event_id=eit.event_id 上左加入 event_inventory_table eit
查询 #2 (MySQL 8.0)
select e.event_id,e.event_name,datediff(e.event_end_date,e.event_start_date)evnt_Duration,product_id,sum(units)over(partition by e.event_id) Units_Sold,sum(units)over(partition by e. event_id,product_id) units_sold_per_product 来自事件 e 在 e.event_id=eit.event_id 上左加入 event_inventory_table eit
输出:
event_id | 事件名称 | evnt_Duration | Units_Sold | units_sold_per_product | product_id |
---|---|---|---|---|---|
1 | 一 | 1 | 15 | 10 | 1 |
1 | 一 | 1 | 15 | 5 | 5 |