简体   繁体   English

SELECT包含条件的情况

[英]SELECT count with condition inside CASE

I am trying to count certain rows of a table when a condition is met. 我试图在满足条件时计算表的某些行。 Below is an example of what am trying to do. 以下是尝试执行的示例。

SELECT (CASE
        WHEN COUNT(*)<9 WHERE (tb1.col IS NULL OR tb1.col=1) THEN 1
        WHEN COUNT(*)<9 WHERE tb1.col=2 THEN 2
        WHEN COUNT(*)<9 WHERE tb1.col=3 THEN 3
        WHEN COUNT(*)<9 WHERE tb1.col=4 THEN 4
        WHEN COUNT(*)<9 WHERE tb1.col=5 THEN 5
        WHEN COUNT(*)<9 WHERE tb1.col=6 THEN 6
    END)
WHERE tb1.id=X

I know its not exactly working like that, but I was wondering, since I have to make 12 more WHEN.. THEN, if there is another way to do it. 我知道它的工作方式并不完全一样,但是我想知道,因为我必须再增加12个时间。然后,是否还有其他方法可以这样做。 Basically am trying to count rows that meet a condition and check if there are less than 9. Repeat that 17 more times. 基本上是试图对满足条件的行进行计数,并检查是否少于9行。再重复执行17次。

Group your data by tb1.col and get the counts of each group. 通过tb1.col对数据进行tb1.col并获取每个组的计数。 Then find the first value that has less than 9. 然后找到小于9的第一个值。

SELECT MIN(col) AS val
FROM (
    SELECT IFNULL(tb1.col, 1) AS col, COUNT(*) AS count
    FROM yourTable AS tb1
    WHERE tb1.id = X
    GROUP BY col
) x
WHERE count < 9

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

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