0

使用如下数据,我需要生成一个报告,报告返回 NULL 的记录数和重复数,如果可能,所有这些都使用一个 SQL 查询。

DES   |  VAL
--------------
Tango |  32
Zulu  |  [null]
Golf  |  12
Golf  |  12
Bravo |  [null]

该报告将如下所示:

NULLS  |  DUPLICATES
---------------------
  2    |    1

我可以使用SUM(CASE VAL WHEN NULL THEN 1 ELSE 0 END) AS NULLS, 和单独的重复项来获取空值,但不能作为一个查询,所以我什至不知道这是否可能。

4

4 回答 4

1
SELECT
  (SELECT COUNT(*) FROM table_name WHERE val IS NULL) 
    AS NULLS,
  (SELECT ( COUNT(val) - COUNT(DISTINCT(val)) ) FROM table_name) 
    AS DUPLICATES
于 2012-05-23T23:18:42.610 回答
0

好吧,如果您有 2 个选择返回标量值,您想将它们组合成一个简单的报告,您可以这样做:

SELECT 
2 AS NULLS,
DUPS
FROM (SELECT 1 AS DUPS) D

结果:

NULLS       DUPS
----------- -----------
2           1

根据需要替换两个选择。

于 2012-05-23T23:17:14.627 回答
0

假设(?!)您想要计算重复行,这可能接近您想要的:

declare @Foo as Table ( DES VarChar(10), VAL Int Null )
insert into @Foo ( DES, VAL ) values
  ( 'Tango', 32 ),
  ( 'Zulu', NULL ),
  ( 'Golf', 12 ), ( 'Golf', 12 ), ( 'Golf', 13 ),
  ( 'Bravo', NULL ),
  ( 'Whiskey', 8388 ), ( 'Whiskey', 8388 ), ( 'Whiskey', 8388 ), ( 'Whiskey', 8388 )

select * from @Foo

select distinct DES, VAL from @Foo

select ( select Count( 42 ) from @Foo where VAL is NULL ) as [NULLS],
  ( select Count( 42 ) from @Foo ) - Count( 42 ) as [DUPLICATES] from ( select distinct DES, VAL from @Foo ) as Elmer
于 2012-05-24T02:24:12.773 回答
0

不知道你想如何计算你的重复,所以我包括了两个版本。

declare @T table
(
  DES varchar(10),
  VAL int
)

insert into @T values
('Tango',   32),
('Zulu',    null),
('Zulu',    null),
('Zulu',    null),
('Golf',    12),
('Golf',    12),
('Bravo',   null)

select sum(case when T.VAL is null then C end) as NULLS,
       sum(case when T.C > 1 then C-1 end) as DUPLICATES1,
       sum(case when T.C > 1 then 1 end) as DUPLICATES2
from (
       select VAL, count(*) as C
       from @T
       group by DES, VAL
     ) T

结果:

NULLS       DUPLICATES1 DUPLICATES2
----------- ----------- -----------
4           3           2
于 2012-05-24T03:53:48.097 回答