表有4个int列(Price0,Price1,Price2,Price3)。
表格示例:
ID | Price0 | Price1 | Price2 | Price3 |
---+--------+--------+--------+--------+
1 | 10 | 20 | NULL | NULL |
2 | 70 | NULL | NULL | NULL |
3 | 30 | 40 | 50 | NULL |
如何查询此表以获取
结果必须是:
Total | Filled
------+-------
3 | 2
此查询显示每行填写的Price filed数量
select
(select count(*) as filledFieldsCount
from (values (T.Price0), (T.Price1), (T.Price2), (T.Price3)) as v(col)
where v.col is not null
)
from Table1 T
答案 0 :(得分:1)
您可以使用条件聚合执行此操作:
select count(*),
sum(case when tt.filledFieldsCount >= 2 then 1 else 0 end)
from Table1 T outer apply
(select count(*) as filledFieldsCount
from (values (T.Price0), (T.Price1), (T.Price2), (T.Price3)) as v(col)
where v.col is not null
) tt;
我使用from
将子查询移动到apply
子句。这是横向连接的示例。在这种情况下,它与子查询做同样的事情。
答案 1 :(得分:1)
在简单的情况下,只有4列只有一个简单的嵌套案例
select count(*),
sum(case when (
CASE WHEN Price1 is null THEN 0 ELSE 1 END +
CASE WHEN Price2 is null THEN 0 ELSE 1 END +
CASE WHEN Price3 is null THEN 0 ELSE 1 END +
CASE WHEN Price4 is null THEN 0 ELSE 1 END) >= 2 then 1 else 0 end)
FROM Table1