代码之家  ›  专栏  ›  技术社区  ›  ravsun

按多列值自定义联合查询顺序

  •  0
  • ravsun  · 技术社区  · 6 年前

    我有一个包含商品销售数据的表格,如下所示:

    Item_Category || Item_Subcategory || Item_ID        || No_of_Sales
    Produce       || Fruits           || Mango          || 13
    Produce       || Fruits           || Apple          || 21
    Produce       || Fruits           || Banana         || 15
    Produce       || Fruits           || Strawberry     || 19
    Produce       || Vegetables       || Onion          || 7
    Produce       || Vegetables       || Potato         || 41
    Produce       || Vegetables       || Carrot         || 32
    Clothing      || Formal           || Suits          || 8
    Clothing      || Formal           || Trousers       || 46
    Clothing      || Formal           || Shirts         || 16
    Clothing      || Partywear        || Designer Suits || 4
    Clothing      || Casual           || Tees           || 11
    Clothing      || Casual           || Jeans          || 23
    Clothing      || Casual           || Jackets        || 17
    Clothing      || Casual           || Turtlenecks    || 33
    Clothing      || Casual           || Belts          || 45
    

    我需要在为其创建联合查询的同一列中显示每个商品类别以及每个商品_子类别的总销售额

    SELECT [Item_Category],
           [Item_Subcategory] AS [Item_Type],
           SUM([No_Of_Sales]) [Number of Sales]
    FROM MyDB.dbo.Item_Sales_Data
    GROUP BY [Item_Category],[Item_Subcategory]
    UNION ALL
    SELECT [Item_Category],
           [Item_Category],
           SUM([No_Of_Sales])
    FROM MyDB.dbo.Item_Sales_Data
    GROUP BY [Item_Category]
    ORDER BY [Item_Category],[Item_Subcategory];
    

    不幸的是,我得到的输出是:

    Item_Category || Item_Type  || No_of_Sales
    Clothing      || Casual     || 129
    Clothing      || Clothing   || 203
    Clothing      || Formal     || 70
    Clothing      || Partywear  || 4
    Produce       || Fruits     || 68
    Produce       || Produce    || 148
    Produce       || Vegetables || 80
    

    预期产出为:

    Item_Category || Item_Type  || No_of_Sales
    Produce       || Produce    || 148
    Produce       || Fruits     || 68
    Produce       || Vegetables || 80
    Clothing      || Clothing   || 203
    Clothing      || Casual     || 129
    Clothing      || Formal     || 70
    Clothing      || Partywear  || 4
    

    我如何做到这一点?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Plamen    6 年前

    您可以添加一个要排序的人工列-尝试以下操作:

    SELECT [Item_Category], [Item_Type],[Number of Sales]
    FROM (
        SELECT [Item_Category],
               [Item_Subcategory] AS [Item_Type],
               SUM([No_Of_Sales]) [Number of Sales],
               0 RN
        FROM dbo.Item_Sales_Data
        GROUP BY [Item_Category],[Item_Subcategory]
        UNION ALL
        SELECT [Item_Category],
               [Item_Category],
               SUM([No_Of_Sales]),
               -1 RN
        FROM dbo.Item_Sales_Data
        GROUP BY [Item_Category]
    ) a
    ORDER BY [Item_Category] desc, RN,[Item_Type];