SQL:返回条件为true的行组

时间:2017-08-16 17:40:51

标签: sql sql-server tsql

我的数据集如下所示:

controller.instance.getData()

我正在尝试返回动作代码为“取消”的PNR的所有行。所以在这种情况下,PNR 1和B的所有行都是4.

我尝试使用Where子句,但这不正确,因为它只返回WHERE行动代码为“取消”的行。我的结果应该是这样的:

PNR    Action Code
-----+-------------
1    |  Book
1    |  Exchange
1    |  Cancel
2    |  Book
2    |  Exchange
3    |  Book
4    |  Book
4    |  Cancel

7 个答案:

答案 0 :(得分:7)

也许从Where子句中的select语句中获取所需的PNR?

Select T1.PNR
      ,T1.[Action Code]
From myTable T1
Where T1.PNR in (
       Select PNR
       from myTable
       where [Action Code] = 'Cancel'
       )

答案 1 :(得分:2)

我认为您需要在表格中进行自我INNER JOIN。 这样的事情:

select      b.*
from        yourtable a
inner join  yourtable b
on          a.PNR = b.PNR
where       a.Action_Code = 'Cancel'

答案 2 :(得分:2)

我不确定我是否得到你的答案,但我认为这应该对你有帮助

select * 
from your_table 
where PNR in (select PNR 
              from your_table 
              where Action_Code like 'Cancel')

答案 3 :(得分:1)

您可以查询如下:

Select * from (
    Select *, SmCnt = Sum(case when [Action Code] = 'Cancel' then 1 else 0 end) over(partition by pnr) 
    from #pnrdata
) a where a.SmCnt > 0

输出如下:

+-----+-------------+
| PNR | Action Code |
+-----+-------------+
|   1 | Book        |
|   1 | Exchange    |
|   1 | Cancel      |
|   4 | Book        |
|   4 | Cancel      |
+-----+-------------+

答案 4 :(得分:0)

你也可以在这里采取CTE路线。

; with cte as (
    select 
    pnr
    ,[action code]
    ,SUM(case
        when [action code] = 'cancel' then 1
        else 0
    end ) OVER(partition by pnr order by pnr) as canceledItem
from test
)
select *
from cte
where canceledItem = 1

答案 5 :(得分:0)

我会这样写,使用CTE使其易于阅读:

WITH RelevantPNRs AS(
    SELECT DISTINCT PNR
    FROM [YourTable]
    WHERE [ActionCode] = 'Cancel'
)
SELECT t.*
FROM [YourTable] t
    INNER JOIN RelevantPNRs r ON t.PNR = r.PNR

答案 6 :(得分:-1)

select * 
from your_table 
where PNR=1 or PNR=4