我在SQL Server 2008中有代码,我需要在另一行中加入一行。
这是代码
select
usuario.SK_Representative,
sum(devo.NM_Material) as deve
from
DW_DTS_Representative usuario
inner join
DIS_DTS_Sales_Return_Fact devo on devo.SK_Representative = usuario.SK_Representative
inner join
DW_DTS_Operation_Nature cfop on cfop.SK_Operation_Nature = devo.SK_Operation_Nature
inner join
DW_DTS_Emitter cli on cli.SK_Emitter = devo.SK_Emitter
where
devo.CD_Currency = '0'
and devo.CD_Site = '001'
and cli.CD_Customer_Group = '10'
and usuario.SK_Representative != '2'
and usuario.SK_Representative != '3'
and usuario.SK_Representative != '4'
and usuario.SK_Representative != '41'
and usuario.SK_Representative != '48'
and usuario.SK_Representative != '49'
and usuario.SK_Representative != '43'
and devo.DT_Day between DateAdd(yyyy, DateDiff(yyyy,0,GetDate()), 0)
and dateadd([month], datediff([month], '18991231', dateadd(month, -1, getdate())), '18991231')
group by
usuario.SK_Representative
该脚本的结果是:
但是我需要将数字'33'的SK_Representative信息聚合到数字'47'的SK_Representative中。我需要这样做而不会丢失主键,即SK_Representative。
答案 0 :(得分:0)
如果我理解你的问题,我相信这就是你想要的。我还考虑了@ juan-carlos-oropeza关于使用usuario.SK_Representative NOT IN
的建议。
select
CASE
WHEN usuario.SK_Representative IN ('33', '47') THEN '47'
ELSE usuario.SK_Representative
END AS SK_Representative,
sum(devo.NM_Material) as deve
from
DW_DTS_Representative usuario
inner join
DIS_DTS_Sales_Return_Fact devo on devo.SK_Representative = usuario.SK_Representative
inner join
DW_DTS_Operation_Nature cfop on cfop.SK_Operation_Nature = devo.SK_Operation_Nature
inner join
DW_DTS_Emitter cli on cli.SK_Emitter = devo.SK_Emitter
where
devo.CD_Currency = '0'
and devo.CD_Site = '001'
and cli.CD_Customer_Group = '10'
AND usuario.SK_Representative NOT IN ('2', '3', '4', '41', '48', '49', '43')
and devo.DT_Day between DateAdd(yyyy, DateDiff(yyyy,0,GetDate()), 0)
and dateadd([month], datediff([month], '18991231', dateadd(month, -1, getdate())), '18991231')
group by
CASE
WHEN usuario.SK_Representative IN ('33', '47') THEN '47'
ELSE usuario.SK_Representative
END AS SK_Representative
希望这能让你走上正确的道路。
诺尔