简体   繁体   English

SQL Server对子查询使用不同的分组依据和排序依据列

[英]SQL Server use Different Group By and Order By Columns with Sub-query

I'm trying to only display certain columns from a group by query using a grouping set. 我正在尝试仅通过使用分组集的查询显示分组中的某些列。 I also want to order by only certain other columns as well. 我也想仅按某些其他列进行排序。

To do this I'm using a sub-query. 为此,我使用了子查询。

I have two questions: 我有两个问题:

  1. Is there a better way to group by and order by diff columns? 有没有更好的方法来对差异列进行分组和排序?

  2. Are there performance problems with using sub-query this way? 通过这种方式使用子查询是否存在性能问题?

Query: 查询:

SELECT Region, State, Sales FROM (
    SELECT RegionID, Region, StateID, State, SUM(Sales) AS Sales 
    FROM Sales 
        GROUP BY 
            GROUPING SETS(
                (RegionId, Region, StateID, State), 
                (StateId, State), 
                ()
            )
    ) As T1 
ORDER BY RegionID, StateID

Reason why I want to do this is because I want to sort by different columns than I'm grouping by. 之所以要这样做,是因为我想按与分组依据不同的列进行排序。 But since I'm using a group by query I have to use all columns. 但是由于我使用的是按查询分组,因此必须使用所有列。

Your query is fine. 您的查询很好。 However, I don't think you need the subquery: 但是,我认为您不需要子查询:

SELECT Region, State, SUM(Sales) AS Sales
FROM Sales
GROUP BY GROUPING SETS( (Region, State), (State), () ) 
ORDER BY MAX(RegionID), MAX(StateID);

You can just use an aggregation function on the ids for ordering purposes. 您可以仅在ID上使用聚合函数以进行订购。

Note that the subquery incurs very little performance penalty. 注意,子查询的性能损失很小。 The only issue I can think of is that the aggregation keys are slightly longer and there might be a very small performance penalty for that. 我能想到的唯一问题是聚合密钥稍长一些,因此性能损失可能很小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM