按列对结果进行分组而不使用group by子句

时间:2013-12-26 18:01:30

标签: sql sql-server-2012

我有以下查询:

SELECT 
   s.nsn,
   CAST(ms.msDli AS VARCHAR) + CAST(pe.peDli AS VARCHAR) as dli,
   p.engineNo, m.mopNo, sh.carName, 
   s.qty, s.msdSr, s.msdUr,
   (SELECT MAX(s.Qty) FROM spares s) MaxQuantity
FROM 
   spares s, mop m, pms p, car sh, subEquipment sub, mainSystem ms, parentEquipment pe, car_parentEquipment spe
WHERE 
    s.mopId = m.mopId 
    AND m.pmsId = p.pmsId 
    AND p.subId = sub.subId 
    AND sub.peId = pe.peId 
    AND sub.shId = sh.shId 
    AND pe.peId = spe.peId 
    AND spe.shId = sh.shId 
    AND pe.msId = ms.msId
ORDER BY 
    s.demandDate DESC, s.nsn

以下列方式返回结果:

nsn dli engineNo    mopNo   carName qty msdSr   msdUr   MaxQuantity
098 58011   235     235     TOYOTA  50  98      98          897
235 58011   235     235     TOYOTA  12  25      235     897
098 55511   98      987     COROLLA 98  98      908         897
897 58011   235     235     TOYOTA  23  897     897     897

我想要的是根据第一栏即NSN

来结合这个结果

所有具有类似NSN的汽车一起显示,最后一列显示最大数量(来自qty.列的最大数量:

例如在上面的示例中,结果应如下所示:

nsn dli engineNo    mopNo   carName qty msdSr   msdUr   MaxQuantity
098 58011   235     235    TOYOTA   98  98      98      98
098 55511   98      987     COROLLA 50  98      908     98
235 58011   235     235     TOYOTA  235 25      235     12
897 58011   235     235     TOYOTA  897 897     897     23

我不想要Group By解决方案,因为它会要求我在group by或aggregate子句中包含所有列,并且无法理解这些混乱,如果可能的话,请帮我解决子查询或联接的问题?


应用Gordon Linoff解决方案

with t as (
    SELECT 
       s.nsn,
       CAST(ms.msDli AS VARCHAR) + CAST(pe.peDli AS VARCHAR) as dli,
       p.engineNo, m.mopNo, sh.carName, 
       s.qty, s.msdSr, s.msdUr,
       (SELECT MAX(s.Qty) FROM spares s) MaxQuantity
    FROM 
       spares s, mop m, pms p, car sh, subEquipment sub, mainSystem ms, parentEquipment pe, car_parentEquipment spe
    WHERE 
        s.mopId = m.mopId 
        AND m.pmsId = p.pmsId 
        AND p.subId = sub.subId 
        AND sub.peId = pe.peId 
        AND sub.shId = sh.shId 
        AND pe.peId = spe.peId 
        AND spe.shId = sh.shId 
        AND pe.msId = ms.msId
    ORDER BY 
        s.demandDate DESC, s.nsn)
    select t.*, max(qty) over (partition by nsn) as MaxQuantity
    from t
    order by nsn;

1 个答案:

答案 0 :(得分:6)

听起来你想要窗口函数max() over。这将获得每个组的最大值,但是,它不是将值分组,而只是将值附加到每一行:

with t as (your query here)
    select t.*, max(qty) over (partition by nsn) as MaxQuantity
    from t
    order by nsn;