【发布时间】:2019-08-19 14:38:20
【问题描述】:
如何归档以下内容?
如果@chk = 0,则在结果中包含第 4 列,否则仅保留 3 列, 如果选择了第 4 列,则第 4 列需要左连接, 并将第 4 列包含在 group by 中
DECLARE @chk AS INT= 0;
SELECT a.Ledgerid,
b.LedgerCity,
CASE WHEN @chk = 0 THEN SUM(a.TotalAmount) ELSE SUM(a.NetAmount) END,
CASE WHEN @chk = 0 THEN c.ledgername END (is it possilbe to completly do not have this column if @chk <> 0)
FROM ExpenseMaster A
LEFT JOIN LedgerAddress AS B ON A.LedgerID = B.LedgerID
LEFT JOIN LedgerMaster AS C ON A.LedgerID = C.LedgerID --This left join is required only if @chk=0, same logic is there in above select statement
GROUP BY A.LedgerID,
B.LedgerCity;
C.LedgerName; -- this 3rd group required only if @chk=0
一些帖子建议在 Group by 中如何使用案例。我尝试了“当@chk=0 然后a.Ledgerid,b.Ledgercity,c.LedgerName 或者a.Ledgerid,b.Ledgercity END 时按情况分组;但这不起作用
【问题讨论】:
-
将
AND @Chk = 0添加到ON子句中? -
只能通过使用 2 个单独的查询和在您的
@chk变量上的if ... else来确定要使用哪个查询来从结果集中遗漏一列。所有其他问题都是完美的,请参阅上面 Larnu 的评论 -
这个查询可能不是单独运行的。将其留空并允许例程的使用者决定如何处理它有什么问题?
标签: sql sql-server