选择查询的SUM然后显示为另一列

时间:2015-04-25 08:33:52

标签: sql-server sql-server-2008 tsql select join

我有这个包含多个产品的表

enter image description here

另一张表格,其中包含上述每种产品的订单

enter image description here

如何组合这些表并获取每个项目的每个ord_Count的总和,并将其显示为另一列,如下所示

enter image description here

总结一下,我有一个包含不同产品的Items表,以及一个Orders表,用于保存Items表中每个产品的订单,然后我想要一个结合两个表并显示我的库存的查询Items表中的每个项目。

2 个答案:

答案 0 :(得分:3)

试试这个:

SELECT SUM(ord_count) AS Item_stock, itm_Code
FROM YourTable
GROUP BY itm_Code

结合两个表:

SELECT SUM(B.ord_count) AS Item_stock, B.itm_Code
FROM YourTable1 AS A
INNER JOIN YourTable2 AS B
    ON A.itm_Code = B.itm_Code
GROUP BY B.itm_Code

答案 1 :(得分:0)

declare @t table (item varchar(20),itemcode varchar(20))
insert into @t (item,itemcode)values ('choco','ckschoc'),('chocowafer','wfrchoc'),('chocostrrae','wfrstr')
declare @tt table (ordcnt int,itemcode varchar(20),dated date)
insert into @tt (ordcnt,itemcode,dated)values (20,'ckschoc','4/24/2015'),(10,'wfrchoc','4/24/2015'),(15,'wfrstr','4/24/2015')
,(30,'ckschoc','4/24/2015'),(20,'wfrstr','4/24/2015')
we can achieve the same result using sub query and corelated join query also

解决方案

select t.itemcode,p.S  from @t t INNER JOIN   (
select itemcode,SUM(ordcnt)S from @tt
GROUP BY  itemcode)P
ON p.itemcode = t.itemcode
group by  t.itemcode,P.s

select t.itemcode,
(select SUM(tt.ordcnt)Cnt from @tt tt 
where tt.itemcode = t.itemcode 
group by tt.itemcode )Cnt from @t t