SQL从表中获取具有特定类型列值

时间:2017-12-15 09:28:54

标签: sql sql-server greatest-n-per-group

我有一张桌子说"包"。

packageid   FlightType
    230         Common
    231          B717
    232          A330
    233          B717
    234         Common
    235          B767
    236          A330
    237          A330
    238          A330
    239          A330
    240          B767
    241          B767
    242          B767

使用SELECT Max(PackageID) AS PackageID, FlightType FROM Packages GROUP BY FlightType,我可以获得每个FlightType的最大packageid,如下所示

PackageID   FlightType
239         A330
233         B717
242         B767
234        Common

但我的要求是一个SQL,它将为每个flightType返回第三高的Packageid。这里常用于所有航班类型。所以应该计算每种航班类型,同时返回值。例如对于FlightTYpe B717,最大PackageID将为234,因此第三大的将是231.对于给定的表,查询的输出应该是

PackageID   FlightType
237         A330
231         B717
240         B767

注意: - 我不要求输出具有第三个最高的packageid,用于' common'。因为它表示所有FlightTypes共有的包。

3 个答案:

答案 0 :(得分:1)

使用此

对于每个FlightType的过滤器

WITH CTE
AS
(
    SELECT
        SeqNo = ROW_NUMBER() OVER(PARTITION BY FlightType ORDER BY PackageId DESC),
        *
        FROM Packages
)
SELECT
    *
    FROM CTE
        WHERE SeqNo = 3

过滤每个PackageType

WITH CTE
    AS
    (
        SELECT
            SeqNo = ROW_NUMBER() OVER(PARTITION BY PackageId ORDER BY FlightType DESC),
            *
            FROM Packages
    )
    SELECT
        *
        FROM CTE
            WHERE SeqNo = 3

将3替换为任意数字以获取每个包的相应记录 例如:1 - 获得最大,2获得第二大等

答案 1 :(得分:1)

如果预期结果是最高位置,直到第3位:

with cte as ( 
    select    packageid
            , flighttype
            , ROW_NUMBER() OVER(Partition by flighttype order by packageid desc) as pos
    from #Packages)
select *
from cte c1
where pos = (select max(c2.pos) from cte c2 where pos<=3 and c1.FlightType = c2.FlightType)

答案 2 :(得分:0)

我认为在你的预期结果中,B717有一个错误,这应该是231而不是230 如果这是正确的,你可以试试这个:

首先让我们创建一个内存表,我们可以在

上进行测试
declare @Packages table (packageid int, flighttype varchar(10))
insert into @Packages (packageid, flighttype)
values (230, 'Common'), (231, 'B717'), (232, 'A330'), (233, 'B717'), (234, 'Common'), (235, 'B767'),
       (236, 'A330'), (237, 'A330'), (238, 'A330'), (239, 'A330'), (240, 'B767'), (241, 'B767'), (242, 'B767')

现在查询:

select distinct p.flighttype,
       (select top 1 p3.packageid from
         ( select top 3 p2.packageid from @packages p2 where p2.flighttype = p.flighttype order by p2.packageid desc ) p3
         order by p3.packageid
       )  
from   @packages p

结果如下:

flighttype  packageid   
----------  ---------   
A330        237 
B717        231 
B767        240 
Common      230 

这将获得所有第3个最大的packageid,如果只有2个,那么它将获得第二个,如果只有一个将获得第一个