2

我有这个查询

SELECT 
    COUNT(
            CASE 
                WHEN restricted LIKE '%us%' THEN 2 
                ELSE 1 
            END) AS totalcount 
FROM 
    reviews 
WHERE 
    restricted LIKE '%us%'

这会计算出现在列中的值(如“我们”)的总数(受限)。此列以这种“不寻常”的方式由来自多选复选框的值填充:

*us*ca*uk* 等

这有效。没问题。

现在,我需要计算这个值(我们)没有出现在哪里。我试图做到这一点,一个“经典”。

SELECT 
    COUNT(
            CASE 
                WHEN restricted NOT LIKE '%us%' THEN 2 
                ELSE 1 
            END
    ) AS totalcount 
FROM 
    reviews 
WHERE 
    restricted NOT LIKE '%us%'

我已经声明了语句 NOT LIKE 但现在......问题......它还计算未填充“受限”列的行(某些列表不使用此列)。而且计数是错误的。

有人可以帮忙吗?

4

4 回答 4

1

这个怎么样?

SELECT 
    COUNT(*) AS totalcount 
FROM 
    reviews 
WHERE 
    restricted IS NOT NULL 
-- In case you expect restricted to contain spaces, the following line should be 
-- LTRIM(RTRIM(restricted)) != ''
AND restricted != '' 
AND restricted NOT LIKE '%us%'

这将过滤掉限制为空或空的行。

于 2012-09-23T12:31:03.697 回答
1

不需要 CASE 语句。您的 WHERE 子句意味着 ELSE 永远不会被击中。

匹配“我们”:

SELECT 
  COUNT(restricted) AS 'Count matching *us*' 
FROM 
  reviews 
WHERE 
  restricted IS NOT NULL 
  AND restricted LIKE '%us%'

不匹配“我们”(包括 null):

SELECT 
  COUNT(restricted) AS 'Count not matching *us*' 
FROM 
  reviews 
WHERE 
  restricted IS NULL 
  OR restricted NOT LIKE '%us%'
于 2012-09-23T13:05:06.620 回答
0

'restricted' 列上的空值或空值将通过“restricted NOT LIKE '%us%'”语句。尝试更改为:

SELECT 
    COUNT(
            CASE 
                WHEN restricted NOT LIKE '%us%' THEN 2 
                ELSE 1 
            END
    ) AS totalcount 
FROM 
    reviews 
WHERE 
    restricted NOT LIKE '%us%' 
    AND restricted != '' 
    AND restricted IS NOT NULL
于 2012-09-23T12:33:11.973 回答
0
SELECT 
    COUNT(*) AS totalcount 
FROM 
    reviews 
WHERE 
    restricted IS NOT NULL 

如果您希望限制包含空格,则以下行应该是

LTRIM(RTRIM(restricted)) != ''
AND restricted != '' 
AND restricted NOT LIKE '%us%'
于 2014-12-08T09:02:06.473 回答