在SQL Server中使用case语句来SELECT AS

时间:2014-06-27 13:21:59

标签: sql sql-server

我有一段代码,我正在连接两个表并选择某些列,其中一列(NetMarkdown)被求和,我希望根据单独列的值将其选择为3个不同的列(MKUP_MKDN_RSN_CD) 。我的代码如下:

SELECT ITEM_ID, MVNDR_PRTY_ID as 'MVNDR_PRTY_ID', sum(NetMarkdown)=(CASE MKUP_MKDN_RSN_CD
WHEN 4 THEN as 'Code4' 
WHEN 23 THEN as 'Code 23'
ELSE as 'Code Other'
END), 
FSCL_WK_DESC INTO ##temp FROM
STRMKDN LEFT JOIN TimeHierarchy
ON CAL_PRD_END_DT=CAL_DT
group by ITEM_ID, MVNDR_PRTY_ID, FSCL_WK_DESC, MKUP_MKDN_RSN_CD

我在第1行中收到错误,说“'''附近的语法不正确。”

我接近这个完全错了吗?接近这个的正确方法是什么?谢谢你的帮助

1 个答案:

答案 0 :(得分:3)

三个单独的总和:

SELECT ITEM_ID, MVNDR_PRTY_ID as 'MVNDR_PRTY_ID',
    sum(CASE WHEN MKUP_MKDN_RSN_CD = 4 THEN NetMarkdown END) as Code4,
    sum(CASE WHEN MKUP_MKDN_RSN_CD = 23 THEN NetMarkdown END) as Code23,
    sum(CASE WHEN MKUP_MKDN_RSN_CD != 4 and
                  MKUP_MKDN_RSN_CD != 23 THEN NetMarkdown END) as CodeOther,
FSCL_WK_DESC INTO ##temp FROM
STRMKDN LEFT JOIN TimeHierarchy
ON CAL_PRD_END_DT=CAL_DT
group by ITEM_ID, MVNDR_PRTY_ID, FSCL_WK_DESC

您现有代码的问题在于您有效地尝试更改结果集中显示的列(例如,假设没有行的原因代码为4) - 您可以'在动态SQL之外做。

目前,如果从未看到特定的原因代码,这将生成NULL - 如果您想避免这种情况,请用SUM(...) COALESCE(SUM(...),0) s >