我目前有一个表,它在一个我无法改变的系统中。所以不是理想的格式,我知道,但我需要计算6列以显示是否输入了某些内容然后将总和放在最后一列中。条目是文本,所以我只需要知道6列中的总数。
[data1]
[data2]
[data3]
[data4]
[data5]
[data6]
--To be created [totalcount]
答案 0 :(得分:1)
如果我理解正确:
select t.*,
( (case when col1 is not null then 1 else 0 end) +
(case when col2 is not null then 1 else 0 end) +
(case when col3 is not null then 1 else 0 end) +
(case when col4 is not null then 1 else 0 end) +
(case when col5 is not null then 1 else 0 end) +
(case when col6 is not null then 1 else 0 end)
) as num_notnull
from t;
答案 1 :(得分:0)
首先要考虑的是空字符串(''
)是否为空。然后,您可以对整个表格执行以下操作:
SELECT
COUNT(CASE WHEN T.Col1 IS NULL OR T.Col1 = '' THEN 1 END) Col1Blanks,
COUNT(CASE WHEN T.Col2 IS NULL OR T.Col2 = '' THEN 1 END) Col2Blanks,
COUNT(CASE WHEN T.Col3 IS NULL OR T.Col3 = '' THEN 1 END) Col3Blanks,
COUNT(CASE WHEN T.Col4 IS NULL OR T.Col4 = '' THEN 1 END) Col4Blanks,
COUNT(CASE WHEN T.Col5 IS NULL OR T.Col5 = '' THEN 1 END) Col5Blanks,
COUNT(CASE WHEN T.Col6 IS NULL OR T.Col6 = '' THEN 1 END) Col6Blanks
FROM
YourTable T
如果你需要所有这些的总和(ISNULL
是一个SQL Server函数,每个DMBS都有一个等价物):
SELECT
X.Col1Blanks,
X.Col2Blanks,
X.Col3Blanks,
X.Col4Blanks,
X.Col5Blanks,
X.Col6Blanks,
ISNULL(X.Col1Blanks, 0) +
ISNULL(X.Col2Blanks, 0) +
ISNULL(X.Col3Blanks, 0) +
ISNULL(X.Col4Blanks, 0) +
ISNULL(X.Col5Blanks, 0) +
ISNULL(X.Col6Blanks, 0) TotalBlanks
FROM
(
SELECT
COUNT(CASE WHEN T.Col1 IS NULL OR T.Col1 = '' THEN 1 END) AS Col1Blanks,
COUNT(CASE WHEN T.Col2 IS NULL OR T.Col2 = '' THEN 1 END) AS Col2Blanks,
COUNT(CASE WHEN T.Col3 IS NULL OR T.Col3 = '' THEN 1 END) AS Col3Blanks,
COUNT(CASE WHEN T.Col4 IS NULL OR T.Col4 = '' THEN 1 END) AS Col4Blanks,
COUNT(CASE WHEN T.Col5 IS NULL OR T.Col5 = '' THEN 1 END) AS Col5Blanks,
COUNT(CASE WHEN T.Col6 IS NULL OR T.Col6 = '' THEN 1 END) AS Col6Blanks
FROM
YourTable T
) X