SQL查询 - 根据条件选择一行或另一行

时间:2017-07-13 08:08:17

标签: sql sql-server

我有以下查询产生给定的结果。

SELECT 
    p.BookingID, p.PaxID, p.LeadPax, p.FirstName AS LeadPaxName
FROM 
    [dbo].[BookingV2_Pax] p
WHERE
    p.[LeadPax] = 1

UNION

SELECT 
    PN.BookingID, PN.PaxID, PN.LeadPax, PN.LeadPaxName
FROM 
    (SELECT 
         p.BookingID, p.PaxID, p.LeadPax, p.FirstName AS LeadPaxName,
         ROW_NUMBER() OVER (PARTITION BY p.BookingID ORDER BY p.PaxID) AS rn
     FROM 
         [dbo].[BookingV2_Pax] p
     WHERE 
         p.[LeadPax] = 0) PN
WHERE 
    PN.rn = 1

结果:

booking pax results

我在这里做的是选择具有LeadPax = true的行,并从具有LeadPax = false的其他行中选择第一行

我想要的是选择LeadPax = 1LeadPax = 0的行。

我了解如果这是与列相关的问题,我可以使用CASECOALESCE,但如何有效地使用行?

此外,任何有关如何优化原始查询的指示都将受到高度赞赏

1 个答案:

答案 0 :(得分:2)

这是一种方式

仅在rs = dbMetaData.getProcedureColumns(packageName, null, procedureName, "%"); 时生成行号。然后使用LeadPax = False逻辑获取相关数据

AND/OR