简体   繁体   English

SQL查询返回最大计数1(如果值为0或-1),否则返回最大计数

[英]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 下面的查询工作正常,我遇到的问题是表A我在该表中的默认值为-1,因此它返回0,但我想要一个可以检查最大计数是否为-的if或case条件1,则应从1开始,否则取最大计数

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 示例:假设表中的最大计数为-1,则为默认值;如果该值不为-1,则应从0开始计数;应获取最大计数

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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