SQL Server 2008 - 按顺序排序分组数据

时间:2014-12-19 14:56:30

标签: sql sql-server-2008

我需要对CustomerAlertName进行分组以获取每个客户提供的警报数量,然后我需要按No_Alerts订购结果。我正在使用这个SQL查询:

SELECT Customer, AlertName, COUNT(AlertName) as No_Alerts
FROM Alerts
GROUP BY Customer, AlertName
ORDER BY Customer, No_Alerts DESC

结果是:

     Customer    AlertName    No_Alerts

----------------------------------
1    Cust1       Alert1       12
2    Cust1       Alert7        5
3    Cust1       Alert5        3
4    Cust2       Alert8       32
5    Cust2       Alert4       17
6    Cust2       Alert2        2
7    Cust3       Alert3      234
8    Cust3       Alert4       22
9    Cust3       Alert6        7

但是如何获得以下结果,以便上面的数据按No_Alerts排序?

     Customer    AlertName    No_Alerts

----------------------------------
1    Cust3       Alert3       234
2    Cust3       Alert4        22
3    Cust3       Alert6         7 
4    Cust2       Alert8        32
5    Cust2       Alert4        17
6    Cust2       Alert2         2
7    Cust1       Alert1        12
8    Cust1       Alert7         5
9    Cust1       Alert5         3

提前致谢!

3 个答案:

答案 0 :(得分:3)

我认为您希望按每个客户的警报总数(最大数量)进行排序。您可以通过添加其他列,使用窗口函数并按以下方式排序来执行此操作:

SELECT Customer, AlertName, COUNT(AlertName) as No_Alerts,
       SUM(COUNT(AltertName)) OVER (PARTITION BY Customer) as TotalCustomerAlerts
FROM Alerts
GROUP BY Customer, AlertName
ORDER BY TotalCustomerAlerts DESC, Customer, No_Alerts DESC;

请注意,order by包括总计和Customer。这样可以处理两个客户总数相同的情况。

如果您确实希望按客户的最大排序,请使用MAX()代替SUM()

如果您不想看到额外的列,请使用子查询或CTE。

答案 1 :(得分:1)

尽管有供应商特定的解决方案,但应该可以嵌套您的SELECTS。

外面的那个有ORDER BY,内层的有剩下的所有:

SELECT * FROM (SELECT ... GROUP BY ...) ORDER BY ...

答案 2 :(得分:0)

您可以在订单上添加另一项:

SELECT Customer, AlertName, COUNT(AlertName) as No_Alerts
FROM Alerts
GROUP BY Customer, AlertName
ORDER BY Customer DESC, COUNT(AlertName) DESC

之前不太确定“No_Alerts”在您的订单中是如何工作的 - 如果您想按列别名进行排序,则需要将其包装在外部查询中,如下所示:

SELECT *
FROM (
    SELECT Customer, AlertName, COUNT(AlertName) as No_Alerts
    FROM Alerts
    GROUP BY Customer, AlertName
) tableThing
ORDER BY Customer DESC, No_Alerts DESC