答案 0 :(得分:1)
您可以通过使用不同的别名连接表来根据其值拆分列。
假设您的表销售字段为shopId,dept,sales
你可以这样做:
select
s1.shopId,
s1.dept, s1.sales grocery_sales,
s2.dept, s2.sales bakery_sales
from
Sales s1, Sales s2
where
s1.shopId = s2.shopId
and s1.dept="grocery"
and s2.dept="bakery"
答案 1 :(得分:1)
declare @PharmTransDateKey int
set @PharmTransDateKey = 20160630
SELECT
ds.StoreName
,SUM(CASE WHEN dro.NetCount < 0 THEN ClaimAmount ELSE 0 END) AS 'Previous Period Adj'
,SUM(CASE WHEN dro.NetCount < 0 THEN 0 ELSE ClaimAmount END) AS 'Todays Sales'
FROM
Final.FactRxBusinessEffectiveDay f
inner join Final.DimRxOutcome dro
on f.RxOutcomeKey = dro.RxOutcomeKey
inner join Final.DimStore ds
on ds.StoreKey = f.StoreKey and
ds.SourceChainKey = 254
WHERE
PharmTransDateKey = @PharmTransDateKey and
dro.NetCount <> 0
GROUP BY
ds.StoreName
我会写PIVOT
,但实际上你会转动一个你可以修改的查询和SUM
CASE STATEMENTS
,并且更简单,更快地得到你的答案。您正在显示的结果与最终所需结果之间无需中介查询。
答案 2 :(得分:0)
调整查询以计算字段,如下所示:
select
ds.StoreName,
sum(case when dro.NetCount < 0 then claimamount end) 'Previous Period Adj'
sum(case when dro.NetCount >= 0 then claimamount end) 'Todays Sales'
from
Final.FactRxBusinessEffectiveDay f
inner join Final.DimRxOutcome dro
on f.RxOutcomeKey = dro.RxOutcomeKey
inner join Final.DimStore ds
on ds.StoreKey = f.StoreKey and
ds.SourceChainKey = 254
where
PharmTransDateKey = @PharmTransDateKey and
dro.NetCount <> 0
group by
ds.StoreName,
order by 1