我有这样的疑问:
select
Customer as Customer,
siteId,
pos,
week,
sum(Inventory) as totalInventory,
sum(Amount) as totalAmount
from Uploads
WHERE Year = 2022
group by Customer, week, siteId, pos;
并返回类似这样的内容:
客户 | 站点ID | 位置 | 周 | 总库存 | 总金额 |
---|---|---|---|---|---|
客户A | id00A1 | 位置A1 | 1 | 67 | 50 |
客户A | id00A2 | posA2 | 1 | 75 | 45 |
客户A | id00A3 | posA3 | 1 | 98 | 88 |
客户B | id00B1 | posB1 | 1 | 67 | 50 |
客户C | id00C1 | posC1 | 1 | 67 | 50 |
客户C | id00C2 | posC2 | 1 | 75 | 45 |
客户B | id00B1 | posB1 | 2 | 67 | 50 |
客户C | id00C1 | posC1 | 2 | 67 | 50 |
客户C | id00C2 | posC2 | 2 | 75 | 45 |
客户B | id00B1 | posB1 | 3 | 67 | 50 |
但是我想根据客户了解上周的数据,而不是每周的数据。像这样的东西:
客户 | 站点ID | 位置 | 周 | 总库存 | 总金额 |
---|---|---|---|---|---|
客户A | id00A1 | 位置A1 | 1 | 67 | 50 |
客户A | id00A2 | posA2 | 1 | 75 | 45 |
客户A | id00A3 | posA3 | 1 | 98 | 88 |
客户C | id00C1 | posC1 | 2 | 67 | 50 |
客户C | id00C2 | posC2 | 2 | 75 | 45 |
客户B | id00B1 | posB1 | 3 | 67 | 50 |
我的查询中缺少什么?
我尝试了以下查询:
select
Customer as Customer,
siteId,
pos,
max(week),
sum(Inventory) as totalInventory,
sum(Amount) as totalAmount
from Uploads
WHERE Year = 2022
group by Customer, week, siteId, pos;
select
Customer as Customer,
siteId,
pos,
max(week),
sum(Inventory) as totalInventory,
sum(Amount) as totalAmount
from Uploads
WHERE Year = 2022
group by Customer, week, siteId, pos
having max(week);
但仍然有相同的结果。
创建表是:
CREATE TABLE Uploads (
id int,
Year int,
Week int,
Division varchar(255),
ProductGroupID varchar(255),
Country varchar(255),
Customer varchar(255),
POS varchar(255),
SiteID varchar(255),
Brand varchar(255),
Product varchar(255),
Inventory int NOT NULL,
SoldUnits int NOT NULL,
Amount float NOT NULL )
我们可以使用子查询来查找每个客户的最新一周。
select
c Customer,
SiteId,
pos,
Week,
sum(inventory) TotalInventory,
sum(amount) TotalAmount
from
(select
customer c,
year y,
max(week) w
from
Uploads
where
year = 2022
group by customer) lastWeek
join
Uploads on c = customer
and y = year and w = week
group by
c, SiteId, pos, week
客户 | 站点 ID | 位置 | 周 | 总库存 | 总金额 |
---|---|---|---|---|---|
客户A | 00A1 | 位置A1 | 1 | 67 | 50 |
客户A | 00A2 | posA2 | 1 | 75 | 45 |
客户A | 00A3 | posA3 | 1 | 98 | 88 |
客户B | 00B1 | posB1 | 3 | 67 | 50 |
客户C | 00C1 | posC1 | 2 | 67 | 50 |
客户C | 00C2 | posC2 | 2 | 75 | 45 |
db\u003c\u003e小提� 75e1 ��这里
\n "