我的要求与此问题和答案类似PostgreSQL - 计算 COUNT() 的 SUM() 但需要另一列的总计
我有类似的东西
create table Item
(
ItemID INTEGER not null,
ItemCode NCHAR(10) not null,
ItemName NCHAR(10) not null,
constraint PK_ITEM primary key (ItemID)
);
create table Store
(
StoreID INTEGER not null,
StoreName NCHAR(20) not null,
ItemID INTEGER not null,
Location NCHAR(20) not null,
constraint PK_STORE primary key (StoreID),
foreign key (ItemID) references Item(ItemID)
);
insert into Item (ItemID,ItemCode,ItemName) Values (1,'abc','abc');
insert into Item (ItemID,ItemCode,ItemName) Values (2,'def','def');
insert into Item (ItemID,ItemCode,ItemName) Values (3,'ghi','ghi');
insert into Store (StoreID,StoreName,ItemID,Location) Values (1,'B1',1,'L1');
insert into Store (StoreID,StoreName,ItemID,Location) Values (2,'B2',2,'L2');
insert into Store (StoreID,StoreName,ItemID,Location) Values (3,'B3',1,'L3');
insert into Store (StoreID,StoreName,ItemID,Location) Values (4,'B4',2,'L1');
insert into Store (StoreID,StoreName,ItemID,Location) Values (5,'B5',3,'L2');
insert into Store (StoreID,StoreName,ItemID,Location) Values (6,'B6',2,'L3');
insert into Store (StoreID,StoreName,ItemID,Location) Values (7,'B7',3,'L1');
insert into Store (StoreID,StoreName,ItemID,Location) Values (8,'B8',1,'L3');
insert into Store (StoreID,StoreName,ItemID,Location) Values (9,'B9',2,'L1');
这个我试过了
select count(I.ItemID), S.ItemID, I.ItemCode, count(S.Location),S.Location
from Store S, Item I where S.ItemId=I.ItemID
group by S.ItemID, I.ItemCode, S.Location ;
结果是这样的
数 | 项目中 | 商品代码 | 数 | 地点 |
---|---|---|---|---|
2 | 1 | abc | 2 | L3 |
1 | 1 | abc | 1 | L1 |
1 | 2 | 定义 | 1 | L3 |
2 | 2 | 定义 | 2 | L1 |
1 | 2 | 定义 | 1 | L2 |
1 | 3 | 吉 | 1 | L2 |
1 | 3 | 吉 | 1 | L1 |
我想要这样的东西,其中显示 itemId 的总数
数 | 项目中 | 商品代码 | 数 | 地点 |
---|---|---|---|---|
3 | 1 | abc | 2 | L3 |
3 | 1 | abc | 1 | L1 |
4 | 2 | 定义 | 1 | L3 |
4 | 2 | 定义 | 2 | L1 |
4 | 2 | 定义 | 1 | L2 |
2 | 3 | 吉 | 1 | L2 |
2 | 3 | 吉 | 1 | L1 |
或者最好是这样
项目中 | 商品代码 | 数 | 地点 |
---|---|---|---|
1 | abc | 2 | L3 |
1 | abc | 1 | L1 |
1 | 总计 | 3 | <------- |
2 | 定义 | 1 | L3 |
2 | 定义 | 2 | L1 |
2 | 定义 | 1 | L2 |
2 | 总计 | 4 | <------- |
3 | 吉 | 1 | L2 |
3 | 吉 | 1 | L1 |
3 | 总计 | 2 | <------- |
如何实现这一目标?
您可以在单个查询中进行单独的选择,并使用
join
或 union
组合结果。对于第一个预期输出,您可以像下面这样查询
select sq1.count, sq1.ItemID, sq2.ItemCode, sq2.count, sq2.Location from (
select S1.ItemID, count(*) as count
from Store S1
group by S1.ItemID
) sq1
inner join (
select S2.ItemID, I.ItemCode, Count(*), S2.Location from Store S2
inner join Item I
on S2.ItemId = I.ItemId
group by S2.ItemID, I.ItemCode, S2.Location
) sq2
on sq1.ItemID = sq2.ItemID
order by sq2.ItemID, sq2.ItemCode;
对于第二个结果,您可以使用此查询
select * from (
select S.ItemID, I.ItemCode, Count(*), S.Location from Store S
inner join Item I
on S.ItemId = I.ItemId
group by S.ItemID, I.ItemCode, S.Location
union
select S2.ItemID, 'Total' as itemcode, Count(*), null
from Store S2
group by S2.ItemID
) sq
order by sq.ItemID, sq.ItemCode;