SQL Query在某些条件上排除记录

时间:2015-02-02 14:13:41

标签: sql-server distinct

我有一种情况,我的表有记录,我想根据我有什么项目从组中提取数据。 下面是一个屏幕截图,第一部分是表中的记录,第二部分是我想要提取数据的方式。 对于ID(如果我有相同的类和组但是对于项目字段),在一条记录上我有ud9而对于其他它是空白的,那么我总是必须用项目拍照。 我可以通过select distinct ID,Class,Group,item from MyTable where ID='A001' and item<>''

获取它

但我还需要其他线路,我怎样才能获得其他线路? 并且不得在没有项目的情况下获得具有相同类别和组的A001的第二行。

enter image description here

3 个答案:

答案 0 :(得分:1)

试试这个。

SELECT ID,
       Class,
       [Group],
       item
FROM   (SELECT Row_number()OVER(partition BY ID, Class, [Group]
                   ORDER BY CASE WHEN item='' THEN 1 ELSE 0 END) rn,
               *
        FROM   MyTable)a
WHERE  rn = 1 

如果每个itemIDClass有多个Group,请使用此

SELECT ID,
       Class,
       [Group],
       item
FROM   (SELECT *,
               CASE WHEN item = '' THEN 1 ELSE 0 END   temp,
               Count(1)OVER(partition BY ID, Class, [Group]) cnt
        FROM   MyTable)a
WHERE  temp = 0
        OR cnt = 1 

答案 1 :(得分:1)

以下是解决方案之一:

DECLARE @t TABLE
    (
      ID CHAR(4) ,
      Class CHAR(1) ,
      gr CHAR(2) ,
      Item CHAR(3)
    )

INSERT  INTO @t
VALUES  ( 'A001', 'A', 'A1', 'ud9' ),
        ( 'A001', 'A', 'A1', '' ),
        ( 'A001', 'B', '', 'ud4' ),
        ( 'A001', 'B', '', '' ),
        ( 'A001', 'D', 'D2', '' ),
        ( 'A002', 'A', 'A1', '' );

WITH    cte
          AS ( SELECT   * ,
                        ROW_NUMBER() OVER ( PARTITION BY ID, Class, gr ORDER BY CASE
                                                              WHEN item = ''
                                                              THEN 1
                                                              ELSE 0
                                                              END ) AS rn,
                        COUNT(*) OVER ( PARTITION BY ID, Class, gr) AS cn
               FROM     @t
             )
SELECT  ID, Class, gr, Item
FROM    cte
WHERE   rn = 1 OR cn = 1

输出:

ID  Class   gr  Item
A001    A   A1  ud9
A001    B       ud4
A001    D   D2     
A002    A   A1     

您的查询将如下所示:

WITH    cte
          AS ( SELECT   * ,
                        ROW_NUMBER() OVER ( PARTITION BY ID, Class, Group ORDER BY CASE
                                                              WHEN item = ''
                                                              THEN 1
                                                              ELSE 0
                                                              END ) AS rn,
                        COUNT(*) OVER ( PARTITION BY ID, Class, gr) AS cn
               FROM     MyTable
             )
SELECT  ID, Class, Group, Item
FROM    cte
WHERE   rn = 1 OR cn = 1

答案 2 :(得分:1)

两个标准,要么是空白,要么是1,请尝试:

select distinct * from table1 t1 where item <> '' OR
(select count(*) from table1 t2 where t1.id=t2.id and 
 t1.class=t2.class and t1.groups=t2.groups) = 1