检查SQL中是否缺少数据

时间:2014-02-28 04:41:22

标签: sql sql-server

我很难知道这是否有解决方案。

我正在尝试检测缺少的每小时数据。样品:

表HRLY_DATA:

NAME          HOUR
Me            0
Me            1
Me            2
Me            3
Me            6
Me            7
You           0
You           1
You           2
You           3
You           4
You           5
You           6
You           7

如你所见,我的[HOUR]数据缺少4和5.我想要一个输出的查询:

NAME          HOUR
Me            4
Me            5

现在,这就是我所拥有的:

SELECT d.NAME, HR FROM HRs c
LEFT OUTER JOIN
   (
   SELECT distinct a.NAME
   FROM HRLY_DATA a
   INNER JOIN
      (
      SELECT NAME FROM
         (
         SELECT NAME, count(*) as CNT
         FROM
            (
            SELECT DISTINCT NAME, HOUR
            FROM HRLY_DATA
            ) as i
         GROUP BY NAME
         ) as ii
      WHERE CNT < 8
      ) as b
   ON a.NAME=b.NAME
   ) as d
ON c.HR=d.HOUR
WHERE d.HOUR IS NULL

的HR

HR
0
1
2
3
4
5
6
7

我收到了这个输出:

NAME          HR
NULL          4
NULL          5

HOUR的数据范围仅为0 - 7 ..

BTW,我正在使用SQL SERVER / MSSQL。

:(

很抱歉,如果我无法清楚地解释我的问题。 :(

1 个答案:

答案 0 :(得分:3)

请尝试:

select 
    distinct x.NAME, number HOUR
From 
    master.dbo.spt_values cross join HRLY_DATA x
where number between 0 and 7
except
select NAME, HOUR FROM HRLY_DATA

由于表HR包含数据0-7,请尝试:

select 
    distinct NAME, HR
From 
    @HR cross join HRLY_DATA 
except
select * from HRLY_DATA