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

Sql server 按多列值自定义联合查询顺序,sql-server,sql-server-2012,Sql Server,Sql Server 2012,我有一个包含商品销售数据的表,如下所示: Item_Category || Item_Subcategory || Item_ID || No_of_Sales Produce || Fruits || Mango || 13 Produce || Fruits || Apple || 21 Produce || Fruits || Banana

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

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

如何实现这一点?

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

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];

非常感谢,@Plamen。工作得很有魅力!