简体   繁体   English

Access 2010 SQL-通过交叉表查询中的聚合函数对行进行排序

[英]Access 2010 SQL— Order rows by aggregate function in crosstab query

I want to see a SUM (Transform Spending) for each of my rows (Category) and pivoted by another field (Media_Type). 我想为每个 (类别)看到一个SUM (转换支出),并由另一个字段 (Media_Type)进行透视。 The code below works fine for this, except for the ORDER BY clause, which I added because I want my output rows to be ordered by the total spending for each row. 除了ORDER BY子句外,下面的代码可以很好地实现这一目的,因为我希望我的输出行按每行的支出进行排序,所以我添加了该代码。

TRANSFORM  Sum([Spending])

SELECT     [Category],
           SUM([Spending])
FROM       [Data]
GROUP BY   [Category]
ORDER BY   SUM([Spending]) DESC

PIVOT      [Media_Type] IN ("TV","Print","Internet")
;

When I add the ORDER BY command, I get the error: 'Cannot have aggregate function in ORDER BY clause'. 当我添加ORDER BY命令时,出现错误:“ ORDER BY子句中不能具有聚合函数”。 How can I work around this and group my rows by and aggregate? 如何解决此问题并将行分组并汇总?

This article suggests that your SQL should work, an alternative (but by no means great) option would be to move your query into the FROM part of another query eg 本文建议您的SQL应该可以工作,另一种选择(但绝不是很好)是将您的查询移至另一个查询的FROM部分,例如

SELECT 
    * 
FROM (
    -- Your Query Here (but you'll have to name the SUM column) --
) x 
ORDER BY 
    columnName DESC` 

I'm guessing Access doesn't have the OVER clause available in SQL Server which could potentially be used otherwise. 我猜想Access在SQL Server中没有OVER子句,否则可能会使用它。

TRANSFORM  Sum([Spending]) 

SELECT [Category], SUM([Spending]) as sum FROM [Data] GROUP BY [Category] ORDER BY sum DESC 从[Data] GROUP BY [Category] ​​ORDER BY sum DESC中选择[Category],SUM([支出])作为总和

PIVOT [Media_Type] IN ("TV","Print","Internet") ; PIVOT [Media_Type] IN(“电视”,“打印”,“互联网”);

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

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