问题描述
|
我的SQL 2005表中有以下数据模式:
MPAN,Date,Reading1,Reading2,Reading3,......,Reading48
134,21/05/11,0.345,0.789
134,22/05/11,0.467
456,1.234
456,0.009,0.534,......
223,........,3.345
223,3.223,1.234,....,0.989
对于每个记录行,具有丢失数据的字段的数量不同。我如何找出每行缺少多少文件的字段(按MPAN和日期分组)。曾经在Google上进行过搜索,似乎有人建议针对类似情况下的存储过程?
请你帮忙
解决方法
select MPAN,Date,sum
(
case when Reading1 is null then 1 else 0 end +
case when Reading2 is null then 1 else 0 end +
case when Reading3 is null then 1 else 0 end
) as NullCount
from T
group by MPAN,Date
,通常的方法是使用CASE
:
SELECT CASE WHEN field_1 IS NULL THEN 1 ELSE 0 END
+ CASE WHEN field_2 IS NULL THEN 1 ELSE 0 END
+ ... AS total_nulls,COUNT(*) as num_rows
FROM table
GROUP BY total_nulls;
使用问题中的分组和字段名称:
SELECT MPAN,SUM(CASE WHEN Reading1 IS NULL THEN 1 ELSE 0 END
+ CASE WHEN Reading2 IS NULL THEN 1 ELSE 0 END
+ ... ) AS total_nulls
FROM table
GROUP BY MPAN,Date;
,SELECT
MPAN,NullCount = COUNT(*) * 48
- COUNT(Reading1)
- COUNT(Reading2)
- COUNT(Reading3)
…
- COUNT(Reading48)
FROM atable
GROUP BY MPAN,Date
,使用case语句计算总和:
select MPAN,date,sum(null_cnt) from (
select MPAN,(case when val1 is null then 1 else 0 end) +
(case when val2 is null then 1 else 0 end) + ...
(case when val48 is null then 1 else 0 end) null_cnt
from ...
) group by MPAN,date
,恐怕你不得不做些丑陋的事情
select MPAN,(
CASE WHEN Reading1 is null then 1 else 0 end +
CASE WHEN Reading2 is null then 1 else 0 end +
CASE WHEN Reading3 is null then 1 else 0 end +
CASE WHEN Reading4 is null then 1 else 0 end +
... +
CASE WHEN Reading48 is null then 1 else 0 end
) as CountOfNulls
from YourTable
,如果您可以更改架构,那么我要做的第一件事就是将其分解为三个表:
\'Readings \',带有ID和名称,值类似于
ID Name
1 Reading1
2 Reading2
...
48 Reading48
这无疑使您可以轻松添加更多内容。
接下来,一个\'MPAN \'表,其中包含\'MPAN \'s,ID,MPAN和日期:
ID MPAN Date
1 134 21/05/11
2 134 22/05/11
最后,是一个\'Score \'表,该表将两者相关联,并包含具有ReadingID,MPANID和Score的分数:
MPANID ReadingID Score
1 3 0.345
1 48 0.789
2 48 0.467
然后,您可以让关系数据库执行其最擅长的工作并利用关系。例如,此查询将获取所有具有Reading2得分的MPAN:
SELECT MPAN.*,Scores.Score
FROM MPAN
JOIN Scores ON Scores.MPANID = MPAN.ID
AND Scores.ReadingID = 2
,用这个
select
MPAN,coalesce(isnull(reading1,0)+isnull(reading2,0)+isnull(reading3,0)+isnull(reading4,0),0)
from
tablename