我在SQL 2005表中有以下数据模式:
MPAN, Date, Reading1, Reading2, Reading3,......, Reading48
134, 21/05/11, , ,0.345 ,......,0.789
134, 22/05/11, , , ,......, 0.467
456, 21/05/11, , , , , 1.234
456, 22/05/11, 0.009 , , 0.534,......
223, 21/05/11, , , ,........, 3.345
223, 22/05/11, 3.223, 1.234, , , ....,0.989
对于每个记录行,有不同数量的字段缺少数据。我怎样才能找出每行丢失数据的文件数(按MPAN和日期分组)。在Google上进行了搜索,似乎有人建议针对类似案例的存储过程?
请帮忙吗?
答案 0 :(得分:1)
通常的做法是使用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, Date,
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;
答案 1 :(得分:1)
SELECT
MPAN,
Date,
NullCount = COUNT(*) * 48
- COUNT(Reading1)
- COUNT(Reading2)
- COUNT(Reading3)
…
- COUNT(Reading48)
FROM atable
GROUP BY MPAN, Date
答案 2 :(得分:0)
使用case语句计算总和:
select MPAN, date, sum(null_cnt) from (
select MPAN, date,
(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
答案 3 :(得分:0)
我担心你不得不做一些丑陋的事情
select MPAN, Date, (
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
答案 4 :(得分:0)
如果你可以改变架构,我要做的第一件事就是把它分成三个表:
带有ID和名称的'读数',值
ID Name
1 Reading1
2 Reading2
...
48 Reading48
这使您可以轻松添加更多内容。
接下来是一个'MPAN'表,其中包含带有ID,MPAN和日期的MPAN:
ID MPAN Date
1 134 21/05/11
2 134 22/05/11
最后,一个“得分”表格将两者联系起来,并将得分与ReadingID,MPANID和得分相对应:
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
答案 5 :(得分:0)
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
答案 6 :(得分:0)
使用此
select
MPAN, Date,
coalesce(isnull(reading1,0)+isnull(reading2,0)+isnull(reading3,0)+isnull(reading4,0),0)
from
tablename