最里层rownumber over partition by,外层rownumber = 1,最外层sum求和

解决方案 »

  1.   

    ----------------------------------------------------------------
    -- Author  :DBA_HuangZJ(發糞塗牆)
    -- Date    :2014-07-23 17:22:59
    -- Version:
    --      Microsoft SQL Server 2012 - 11.0.5058.0 (X64) 
    -- May 14 2014 18:34:29 
    -- Copyright (c) Microsoft Corporation
    -- Enterprise Edition: Core-based Licensing (64-bit) on Windows NT 6.3 <X64> (Build 9600: ) (Hypervisor)
    --
    ----------------------------------------------------------------
    --> 测试数据:[huang]
    if object_id('[huang]') is not null drop table [huang]
    go 
    create table [huang]([ProID] int,[AttrCateName] varchar(4),[AttrName] varchar(4),[Price] numeric(4,2),[Sort] int)
    insert [huang]
    select 1,'颜色','纯白',10.00,2 union all
    select 1,'颜色','酒色',15.00,1 union all
    select 1,'颜色','青色',12.00,3 union all
    select 1,'装订','平装',5.00,5 union all
    select 1,'装订','精装',15.00,4
    --------------开始查询--------------------------
    SELECT SUM([Price])[Price]
    FROM (
    select *,ROW_NUMBER()OVER(PARTITION BY [AttrCateName] ORDER BY sort)id
    from [huang])a
    WHERE id=1
    ----------------结果----------------------------
    /* 
    Price
    ---------------------------------------
    30.00
    */
      

  2.   

    另一种,AttrCateName分组having Sort = min(Sort),外层再用sum求和
      

  3.   

    只group by AttrCateName ,无法在having 里使用其他非聚合字段