我有一个列名检查,数据类型为bit(true或False),我想要做的是计算列中有多少false和true。
SELECT
COUNT(FeatureState) AS tot_true,
COUNT(*)-COUNT(FeatureState) AS tot_false
FROM productDetail
WHERE FeatureState= 1
这有效
答案 0 :(得分:4)
怎么样;
SELECT
COUNT(CASE fld WHEN 0 THEN 1 ELSE NULL END) AS ZEROS,
COUNT(CASE fld WHEN 1 THEN 1 ELSE NULL END) AS ONES
FROM
T
--alternative
SELECT
SUM(CASE fld WHEN 0 THEN 1 ELSE 0 END) AS ZEROS,
SUM(CASE fld WHEN 1 THEN 1 ELSE 0 END) AS ONES
FROM
T
答案 1 :(得分:2)
试试这个,应该有效:
SELECT
COUNT(field) AS tot_true,
COUNT(*)-COUNT(field) AS tot_false
FROM table
WHERE field=1
答案 2 :(得分:2)
我使用SIGN将位更改为int
SELECT
SUM(SIGN(field)) AS tot_true,
SUM(1-SIGN(field)) AS tot_false
FROM table
或者使用COUNT忽略NULL的事实
SELECT
COUNT(NULLIF(field, 0)) AS tot_true,
COUNT(NULLIF(field, 1)) AS tot_false
FROM table
如果您想要其他值MAX(SomeOtherField),其中最高值来自在其他解决方案中过滤掉的“false”行,则此方法有效
答案 3 :(得分:2)
SELECT
SUM(CASE WHEN FeatureState = 1 THEN 1 ELSE 0 END) AS TrueCount,
SUM(CASE WHEN FeatureState = 0 THEN 1 ELSE 0 END) AS FalseCount,
SUM(CASE WHEN FeatureState IS NULL THEN 1 ELSE 0 END) AS NullCount,
COUNT(1) AS TotalCount
FROM ProductDetail