sql根据列中值的组合获取行

时间:2015-04-09 17:09:01

标签: sql sql-server

Status      Agency  Policy  
---------   ------  ------
Submitted   Ag1     AAA

Rated       Ag1     AAA 

Lost        Ag1     AAA 

Issued      Ag1     AAA 

Submitted   Ag1     BBB 

Rated       Ag1     BBB 

Lost        Ag2     BBB 

Issued      Ag1     BBB 

我有这些数据,例如...... “对于一项政策,如果同一机构既有失物招领又有遗失,那么我不想要失去记录 但如果政策既丢失又从不同的代理机构发出,那么我想要所有的记录

结果集:

Status      Agency  Policy  
---------   ------  ------
Submitted   Ag1     AAA

Rated       Ag1     AAA 

Issued      Ag1     AAA 

Submitted   Ag1     BBB 

Rated       Ag1     BBB 

Lost        Ag2     BBB 

Issued      Ag1     BBB 

2 个答案:

答案 0 :(得分:0)

下面的子句执行以下操作:
当状态未丢失时,请始终返回记录 当状态丢失时,请检查代理商是否没有任何代理机构与“失去的”组合。和'发布'返回记录。

DECLARE @t  TABLE(  [Status] NVARCHAR(50),
                    Agency   NVARCHAR(50),
                    Policy   NVARCHAR(50))


INSERT INTO @t
VALUES(
'Submitted',    'Ag1',     'AAA'),
('Rated',       'Ag1',     'AAA'), 
('Lost',        'Ag1',     'AAA'), 
('Issued',      'Ag1',     'AAA'), 
('Lost',        'Ag2',     'AAA'), 
('Submitted',   'Ag1',     'BBB'), 
('Rated',       'Ag1',     'BBB'), 
('Lost',        'Ag2',     'BBB'), 
('Issued',      'Ag1',     'BBB'), 
('Lost',        'Ag0',     'CCC')

--In the bellow "Select", replace "@t" with your table.
SELECT *
FROM @t AS t
WHERE NOT EXISTS (  SELECT 1
                    FROM   @t AS sub
                    WHERE  sub.Policy = t.Policy
                    AND    sub.Agency = t.Agency
                    AND    sub.[Status] = 'Issued' )
OR [Status] NOT IN ('Lost', 'Declined')

结果:

Submitted   Ag1 AAA
Rated       Ag1 AAA
Issued      Ag1 AAA
Lost        Ag2 AAA
Submitted   Ag1 BBB
Rated       Ag1 BBB
Lost        Ag2 BBB
Issued      Ag1 BBB
Lost        Ag0 CCC

答案 1 :(得分:0)

相关子查询可用于过滤" Lost"匹配"发布"记录存在于同一机构和政策中。

SELECT  Status, Agency, Policy
FROM    YourTable AS t1
WHERE   Status NOT IN ( 'Lost', 'Declined' )
OR      NOT EXISTS (
            SELECT 1
            FROM   YourTable AS t2
            WHERE  t2.Agency = t1.Agency
            AND    t2.Policy = t1.Policy
            AND    t1.Status IN ( 'Lost', 'Declined' )
            AND    t2.Status = 'Issued' )