2015-10-19 76 views
0

我有4个表我想加入以显示出售的物品和返回的物品。我遇到的问题是已售出和退回的商品处于同一张表格中,并且当某件商品没有退货且零售价为“已售出”列时,我们无法为“退货”列返回0一件物品没有销售就退货。这里就是我想要做的,按列值拆分表

位置

LocationID LocationName 
    1   NY 
    2   LA 
    3  Chicago 

项目

ItemID ItemName 
    A Sandwich 
    B Salad 
    C  Wrap 

交付

DeliveryID LocationID 
    1   1 
    2   2 
    3   3 
    4   1 

DeliveryRecords

RecordID DeliveryID ItemID Quantity RecordType 
    1   1  A  3  SOLD 
    2   1  B  4  SOLD 
    3   1  C  5  SOLD 
    4   1  C  2  RETURN 
    5   2  A  3  SOLD 
    6   2  B  2  SOLD 
    7   3  B  2  SOLD 
    8   3  C  3  SOLD 
    9   4  A  1  RETURN 

而且我想我的查询返回,

Location DeliveryID Item  Sold Returned 
    NY   1  Sandwich  3  0 
    NY   1   Salad  4  0 
    NY   1   Wrap  5  2 
    LA   2  Sandwich  3  0 
    LA   2   Salad  2  0 
Chicago  3   Salad  2  0 
Chicago  3   Wrap  3  0 
    NY   4   Wrap  0  1 
+1

什么是查询你试过了吗? –

回答

2

我觉得你只是想有条件的聚合(一串连接后):

select l.locationname, dr.deliveryid, i.itemname, 
     sum(case when dr.recordtype = 'SOLD' then quantity else 0 end) as sold, 
     sum(case when dr.recordtype = 'RETURN' then quantity else 0 end) as returned 
from deliveryrecords dr join 
    deliveries d 
    on dr.deliveryid = d.deliveryid join 
    location l 
    on d.locationid = l.locationid join 
    items i 
    on dr.itemid = i.itemid 
group by l.locationname, dr.deliveridy, i.itemname; 
+0

谢谢,这是完美的! –

1

使用JOINSUM

SQL Fiddle

SELECT 
    l.LocationName, 
    dr.DeliveryID, 
    i.ItemName, 
    [Sold]  = SUM(CASE WHEN dr.RecordType = 'SOLD' THEN dr.Quantity ELSE 0 END), 
    [Returned] = SUM(CASE WHEN dr.RecordType = 'RETURN' THEN dr.Quantity ELSE 0 END) 
FROM DeliveryRecords dr 
INNER JOIN Items i 
    ON i.ItemID = dr.ItemId 
INNER JOIN Deliveries d 
    ON d.DeliveryID = dr.DeliveryID 
INNER JOIN Locatins l 
    ON l.LocationID = d.LocationId 
GROUP BY 
    dr.DeliveryID, l.LocationName, i.ItemName