按列值拆分表

时间:2015-10-19 01:45:12

标签: sql sql-server tsql select join

我想加入4个表来显示已售出的商品和退回的商品。我遇到的问题是售出和退回的商品都在同一张表中,当一件商品没有退货时卖回“退货”栏时我遇到了麻烦在没有销售的情况下退回商品。这是我正在尝试做的事情,

位置

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

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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