SQL从不同列

时间:2015-06-22 03:26:44

标签: sql

我试图让查询显示结果如下,但我无法做到。

Salestable

receipt    product    saletype    qtysold    sellprice    discount
------------------------------------------------------------------
31103    - sugar  ------ I ------- 1 ------ 25 --------    0
31103    - sugar ------- W ------- 1 ------- 0 ---------   3
31103    - milk  ------- I ------- 1 ------ 39 --------    0
31103    - milk  ------- W ------  1 ------- 0 ---------   3

我的查询:

Select 
    receipt, product,
    qty sold, (where saletype='I')
    sellprice, (where saletype='I')
    discount (where salestype='W')
from 
    salestable

所以我的结果如下所示。

Receipt  Product  Qtysold Sellprice Discount
------------------------------------------------
31103  --- sugar ---- 1   ------ 25  --------- 3
31103  --- milk ------ 1  ------ 39---------- 14

3 个答案:

答案 0 :(得分:0)

请注意,只有成对数据才会有效。否则你将不得不相应调整外部适用。

Select a.receipt, a.product, x.QtySold, x.SellPrice, y.discount
(
 select distinct receipt, product from salestable
) a 
outer apply (
  Select B.QtySold, B.SellPrice from salestable B WHERE A.receipt = B.receipt AND A.product = B.product AND b.SALETYPE = 'I'
) x

outer apply (
 Select B.discount  from salestable B WHERE A.receipt = B.receipt AND A.product = B.product AND b.SALETYPE = 'W'
) y

答案 1 :(得分:0)

所以你正走在正确的轨道上。

select
receipt,
product,
max(case when salestype='I' then sellprice else null end) as SellPrice,
max(case when salestype ='I' then qty_sold else null end) as QtySold,
max(case when salestype = 'W' then discount else null end) as discount
from
salestable
group by 
receipt,
product

答案 2 :(得分:0)

您的查询应该是这样的:

yield