简体   繁体   中英

Sql query return the max count 1 if the value is 0 or -1 else take the max count

This below query working fine the issue I am having is with the tableA I have a default value in that table which is -1, so it is returning 0 but what I want an if or case condition that can check if the max count is -1 then it should start with 1 else take whatever the max count

SELECT column1, column2,column3,
    coalesce((SELECT max(columnid)
    FROM tableA),1) 
               + row_number() OVER (ORDER BY user) columnid
               FROM (SELECT columnid,
                            column3,column2,
                            row_number() OVER (PARTITION BY column3
                                               ORDER BY user) rn
                            FROM  tableB) t
               WHERE rn = 1

Example: Let suppose we have max count is -1 in table its a default value it should start the count from 0 if the value is not -1 it should get the max count

You can just change

coalesce((SELECT max(columnid)
    FROM tableA),1)  

to:

CASE WHEN coalesce((SELECT max(columnid)
    FROM tableA),1) =-1 THEN 0 ELSE coalesce((SELECT max(columnid)
    FROM tableA),1)  END

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