以下代码有效,但我想在查询结果中添加“segvalue1”列:
SELECT (SELECT SUM(DebitAmount-CreditAmount) as BalanceAmtCYTD
FROM GLJrnDtl WITH (NOLOCK) WHERE FiscalPeriod between 1 AND 10
AND Company = 'NVV' AND FiscalYear = 2017),
(SELECT SUM(DebitAmount-CreditAmount) as BalanceAmtCYM
FROM GLJrnDtl WITH (NOLOCK) WHERE FiscalPeriod = 10
AND Company = 'NVV' AND FiscalYear = 2017)
所以我将代码修改为如下所示,但它给了我2“当子查询未引入EXISTS时,只能在选择列表中指定一个表达式”错误:
SELECT (SELECT SUM(DebitAmount-CreditAmount) as BalanceAmtCYTD,
segvalue1 FROM GLJrnDtl WITH (NOLOCK) WHERE FiscalPeriod
between 1 AND 10 AND Company = 'NVV' AND FiscalYear = 2017
GROUP BY segvalue1),
(SELECT SUM(DebitAmount-CreditAmount) as BalanceAmtCYM,
segvalue1 FROM GLJrnDtl WITH (NOLOCK) WHERE FiscalPeriod = 10
AND Company = 'NVV' AND FiscalYear = 2017
GROUP BY segvalue1)
有谁知道如何修改代码以获得我想要的结果?再次,我只是想拉入segvalue1列。一旦我搞清楚了,我还会提供更多列。谢谢你的帮助!
答案 0 :(得分:2)
考虑条件聚合:
SELECT segvalue1,
SUM(CASE WHEN FiscalPeriod BETWEEN 1 AND 10
THEN DebitAmount-CreditAmount
ELSE NULL
END) as BalanceAmtCYTD,
SUM(CASE WHEN FiscalPeriod = 10
THEN DebitAmount-CreditAmount
ELSE NULL
END) as BalanceAmtCYM
FROM GLJrnDtl WITH (NOLOCK)
WHERE Company = 'NVV' AND FiscalYear = 2017 -- SHARED CONDITION
GROUP BY segvalue1