如何按指定的聚合值订购此结果集?

时间:2016-09-14 22:47:38

标签: sql-server sum sql-order-by

我有这个问题:

Select top 10 PAItemCode, PADescription, Sum(Qty) as 'Qty'
from Invoice
where Unit = 'Sodexo'
group by PADescription, PAItemCode

...这就是我想要的,除了我需要根据最后一列中的val(Sum(Qty)为'Qty')对结果进行排序desc)

有了这个:

Select top 10 PAItemCode, PADescription, Sum(Qty) as 'Qty'
from Invoice
where Unit = 'Sodexo'
group by PADescription, PAItemCode
order by Qty

...所有Qtys都是0(否则不是)。当我在单引号中包含“数量”时也是如此:

. . .
order by Qty

如何通过聚合值降序来获得此结果集?

4 个答案:

答案 0 :(得分:8)

您还必须按顺序包含SUM(数量),但我的意见是与声明/ CTE一起使用,它更具可读性,您也可以应用其他分组数据的逻辑

如果您在select语句中使用了任何同意函数,并且您还希望在 GROUP BY ORDER BY 中使用该函数,则必须同时应用相同的逻辑。< / p>

SELECT 
    TOP 10 PAItemCode, 
    PADescription, 
    Sum(ISNULL(Qty,0)) as 'Qty'
FROM Invoice
WHERE Unit = 'Sodexo'
GROUP BY PADescription, PAItemCode
ORDER BY Sum(ISNULL(Qty,0))

替代方式使用CTE / With声明:

;WITH T AS
(
    SELECT 
        TOP 10 PAItemCode, 
        PADescription, 
        Sum(ISNULL(Qty,0)) as 'Qty'
    FROM Invoice
    GROUP BY PADescription, PAItemCode
    WHERE Unit = 'Sodexo'
)
SELECT 
    T.PAItemCode,
    T.PADescription,
    T.Qty
FROM T  
ORDER BY T.Qty

答案 1 :(得分:2)

Select top 10 PAItemCode, PADescription, Sum(Qty) as 'Qty'
from Invoice
where Unit = 'Sodexo'
group by PADescription, PAItemCode
order by Sum(Qty) desc

这应该有效

答案 2 :(得分:1)

代码的问题与聚合和别名列中使用的列具有相同的名称。将别名列名重命名为其他名称,并按此新别名命名

答案 3 :(得分:0)

这是在研究MySQL。 您可以尝试的一件事是更改别名如下:

Select PAItemCode, PADescription, Sum(Qty) as 'Qtysum' 
from Invoice 
group by PADescription, PAItemCode 
order by Qtysum desc