如何在select语句中选择count()

时间:2018-09-18 20:43:30

标签: mysql sql

经过数小时的尝试,我终于同意我需要帮助。

我正在尝试从TableA中选择一行,然后计算该行中不为空的单元格的数量。

我知道这是错误的,但可以传达我的意图

SELECT COUNT(colName), 
    (SELECT (column1, column2, column3, column4) AS colName 
     FROM TableA 
     WHERE location= location) 
AS colCount
FROM TableA  
WHERE colName IS NOT NULL  

3 个答案:

答案 0 :(得分:1)

可能有一个更有趣的方法,但蛮力的方法是:

SELECT
   location, 
    CASE WHEN column1 IS NULL THEN 0 ELSE 1 END + 
    CASE WHEN column2 IS NULL THEN 0 ELSE 1 END + 
    CASE WHEN column3 IS NULL THEN 0 ELSE 1 END + 
    CASE WHEN column4 IS NULL THEN 0 ELSE 1 END
   AS colCount 
 FROM TableA 

答案 1 :(得分:1)

SQL DEMO

SELECT id, 
       (`column1` IS NOT NULL) + 
       (`column2` IS NOT NULL) + 
       (`column3` IS NOT NULL) as notnull
FROM Table1

答案 2 :(得分:0)

select location,
    sum(case when column1 is not null then 1 else 0 end) +
    sum(case when column2 is not null then 1 else 0 end) +
    sum(case when column3 is not null then 1 else 0 end) +
    sum(case when column4 is not null then 1 else 0 end) cnt
from TableA
group by location