假设我有这个:
id | col1 | col2 | col3 | col4 | col5 | name
1 | xxx | xxx | xxx | | xxx | John
2 | | | | xxx | xxx | Peter
3 | xxx | xxx | xxx | | | Sam
我如何得到这样的结果:
id | filledData | name
1 | 4 | John
2 | 2 | Peter
3 | 3 | Sam
基本上,我想使用设置列来确定数据的填充程度如何,然后对其进行排序,以便我可以尝试用最少量的数据填充列?< / p>
答案 0 :(得分:1)
您只需使用CASE
语句检查列是否为空。
SELECT ID,
name,
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 filledData
FROM tableName
答案 1 :(得分:0)
这需要一个复杂的案例陈述:
select id, filledData, name
from (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)
) as filledData
from t
) t