如果2018年的销售额为0,我需要将2019年的销售额放入一个名为new的单独列中。在这里我的代码供您参考
SELECT
ISNULL(sp.Telephone,'No Sales Employee'),
od.CardCode,
od.CardName,
Sum(case when c.U_ItemStatus = '2' then od.DocTotal else 0 end) as Sold2018,
Sum(case when c.U_ItemStatus = '1' then od.DocTotal else 0 end) as Sold2019,
(select od.DocTotal where c.U_ItemStatus = '2' ) as new
FROM
ORDR od
Left Join OSLP sp
On od.SlpCode=sp.SlpCode
left join RDR1 a on a.DocEntry = od.DocEntry
left join OITM b on b.ItemCode = a.ItemCode
left Join OITB c on c.ItmsGrpCod = b.ItmsGrpCod
Group By
sp.Telephone,
od.CardCode,
od.CardName,
c.U_ItemStatus,
od.DocTotal
答案 0 :(得分:1)
使用CASE
语句,请注意,您需要在条件中使用Sold2018
的整个表达式,而不是alias
CASE WHEN Sum(case when c.U_ItemStatus = '2' then od.DocTotal else 0 end) = 0
THEN Sum(case when c.U_ItemStatus = '1' then od.DocTotal else 0 end)
END AS New
答案 1 :(得分:1)
您可以使用
SELECT
ISNULL(sp.Telephone,'No Sales Employee') ,
od.CardCode,
od.CardName,
Sum(case when c.U_ItemStatus = '2' then od.DocTotal else 0 end) as Sold2018,
Sum(case when c.U_ItemStatus = '1' then od.DocTotal else 0 end) as Sold2019,
CASE WHEN Sum(case when c.U_ItemStatus = '2' then od.DocTotal else 0 end) = 0 THEN
Sum(case when c.U_ItemStatus = '1' then od.DocTotal else 0 end) END as new
FROM
ORDR od
Left Join OSLP sp
On od.SlpCode=sp.SlpCode
left join RDR1 a on a.DocEntry = od.DocEntry
left join OITM b on b.ItemCode = a.ItemCode
left Join OITB c on c.ItmsGrpCod = b.ItmsGrpCod
Group By
sp.Telephone,
od.CardCode,
od.CardName,
c.U_ItemStatus
或
SELECT *, CASE WHEN Sold2018 = 0 THEN Sold2019 END as new
FROM (
SELECT
ISNULL(sp.Telephone,'No Sales Employee') as Telephone,
od.CardCode,
od.CardName,
Sum(case when c.U_ItemStatus = '2' then od.DocTotal else 0 end) as Sold2018,
Sum(case when c.U_ItemStatus = '1' then od.DocTotal else 0 end) as Sold2019
FROM
ORDR od
Left Join OSLP sp
On od.SlpCode=sp.SlpCode
left join RDR1 a on a.DocEntry = od.DocEntry
left join OITM b on b.ItemCode = a.ItemCode
left Join OITB c on c.ItmsGrpCod = b.ItmsGrpCod
Group By
sp.Telephone,
od.CardCode,
od.CardName,
c.U_ItemStatus
) AS T