简体   繁体   中英

Case when in Select, Left Join and Group By

how can i archive the following?

If @chk = 0 then include 4th Column in result else keep only 3 Columns, and if 4th Column is selected then Left join is needed for that 4th column, and include that 4th column in 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

some posts suggested how to use case when in Group by. I tried "group by case when @chk=0 then a.Ledgerid,b.Ledgercity,c.LedgerName else a.Ledgerid,b.Ledgercity END; but this did not work

Use IF .. ELSE block

IF @chk = 0 
BEGIN

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  
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;


END
ELSE
BEGIN

SELECT a.Ledgerid, 
       b.LedgerCity,
       CASE WHEN @chk = 0 THEN SUM(a.TotalAmount) ELSE SUM(a.NetAmount) END    
FROM ExpenseMaster A
LEFT JOIN LedgerAddress AS B ON A.LedgerID = B.LedgerID
GROUP BY A.LedgerID, B.LedgerCity;


END

If you are sure, that no one from outside of the database can run your query and perform sql-injection, just use the simple dynamic-sql statement

DECLARE @sql AS NVARCHAR(MAX);
DECLARE @chk AS INT= 0;

set @sql = N'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 ' ELSE ' ' END +
        'FROM ExpenseMaster A
             LEFT JOIN LedgerAddress AS B ON A.LedgerID = B.LedgerID ' +
             CASE WHEN @chk=0 THEN 'LEFT JOIN LedgerMaster AS C ON A.LedgerID = C.LedgerID ' ELSE '' END +
        'GROUP BY A.LedgerID, 
                 B.LedgerCity' +
                 CASE WHEN @chk = 0 THEN ', C.LedgerName;' ELSE ';' END;

exec sp_executesql @sql

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM