我有一个以事务为事实表的星型模式。
对于每个产品列表,麦迪逊供应商向芝加哥消费者的销售数量与芝加哥供应商向麦迪逊消费者的销售数量(结果列:产品名称,麦迪逊芝加哥数量,芝加哥麦迪逊数量)
我已经尝试过相交和结合所有
SELECT
P.Name as Product
, SUM(T.Quantity) as QMad
, dbo.Tb_Consumer C
, dbo.Tb_Supplier S
, dbo.Tb_Transactions T
where P.Prod_ID = T.Prod_ID
and C.Con_ID = T.Con_ID
and S.Supp_ID = T.Supp_ID
and S.City = 'Madison'
and C.City = 'Chicago'
from dbo.Tb_Product P
group by P.Name
union all
SELECT P.Name as Product
, sum(T.Quantity) as QCHI
from dbo.Tb_Product P
, dbo.Tb_Consumer C
,dbo.Tb_Supplier S
,dbo.Tb_Transactions T
where P.Prod_ID = T.Prod_ID
and C.Con_ID = T.Con_ID
and S.Supp_ID = T.Supp_ID
and S.City = 'Chicago'
and C.City = 'Madison'
group by P.Name
期待以下内容
Product chi_qy Mad_qy
-------------------------
Auto 3 2
但我明白了
Product chi_qy
-----------------
Auto 3
Auto 2
答案 0 :(得分:0)
只连接两个查询而不是联合 像这样:
select X.Product,QMad,QCHI
from(
SELECT
P.Name as Product
, SUM(T.Quantity) as QMad
from dbo.Tb_Product P
, dbo.Tb_Consumer C
, dbo.Tb_Supplier S
, dbo.Tb_Transactions T
where P.Prod_ID = T.Prod_ID
and C.Con_ID = T.Con_ID
and S.Supp_ID = T.Supp_ID
and S.City = 'Madison'
and C.City = 'Chicago'
from dbo.Tb_Product P
group by P.Name) X
inner join
(SELECT P.Name as Product
, sum(T.Quantity) as QCHI
from dbo.Tb_Product P
, dbo.Tb_Consumer C
,dbo.Tb_Supplier S
,dbo.Tb_Transactions T
where P.Prod_ID = T.Prod_ID
and C.Con_ID = T.Con_ID
and S.Supp_ID = T.Supp_ID
and S.City = 'Chicago'
and C.City = 'Madison'
group by P.Name) Y on X.Product=Y.Product
如果每边都为空白,则可以使用left,right或完全外部联接