我是SQL的新手,所以这可能是一个非常常见/简单的问题, 我想从最高到最低排序,而不是第1组,第2组,第3组。请参阅下文:
SQL
Select (select SUM(Amt) from Tracker W JOIN Teams T ON W.Username = T.Name where T.Team = '1' and W.Activity = '2' ) AS Team1,
(select SUM(Amt) from Tracker W JOIN Teams T ON W.Username = T.Name where T.Team = '2' and W.Activity = '2' ) AS Team2,
(select SUM(Amt) from Tracker W JOIN Teams T ON W.Username = T.Name where T.Team = '3' and W.Activity = '2' ) AS Team3,
(select SUM(Amt) from Tracker W JOIN Teams T ON W.Username = T.Name where T.Team = '4' and W.Activity = '2' ) AS Team4,
(select SUM(Amt) from Tracker W JOIN Teams T ON W.Username = T.Name where T.Team = '5' and W.Activity = '2' ) AS Team5,
(select SUM(Amt) from Tracker W JOIN Teams T ON W.Username = T.Name where T.Team = '6' and W.Activity = '2' ) AS Team6,
(select SUM(Amt) from Tracker W JOIN Teams T ON W.Username = T.Name where T.Team = '7' and W.Activity = '2' ) AS Team7,
(select SUM(Amt) from Tracker W JOIN Teams T ON W.Username = T.Name where T.Team = '8' and W.Activity = '2' ) AS Team8,
(select SUM(Amt) from Tracker W JOIN Teams T ON W.Username = T.Name where T.Team = '9' and W.Activity = '2' ) AS Team9,
(select SUM(Amt) from Tracker W JOIN Teams T ON W.Username = T.Name where T.Team = '10' and W.Activity = '2' ) AS Team10
现在结果显示如下:
我希望它显示最高到最低而不是球队名称。这可以通过Order By完成吗?我似乎无法让它发挥作用。
Team 2 - 597,Team 7 - 540,Team 3 - 467等
答案 0 :(得分:1)
Order by
是基于行的操作,而不是基于列的操作。您可以做的是将此查询转换为基于行并按值排序。
select * from (
select SUM(Amt) as Amt, 'Team1' as Team from Tracker W JOIN Teams T ON W.Username = T.Name where T.Team = '1' and W.Activity = '2'
union
select SUM(Amt), 'Team2' from Tracker W JOIN Teams T ON W.Username = T.Name where T.Team = '2' and W.Activity = '2'
...) as T
order by Amt
答案 1 :(得分:1)
与上面提到的Aaron Bertrand一样,ORDER BY不适用于单行。
您可能希望像这样更改您的查询
select T.Team ,SUM(Amt) as TeamTotal
from Tracker W
JOIN Teams T
ON W.Username = T.Name
where W.Activity = '2'
AND (ISNUMERIC(T.Team) = 1 AND CAST(T.Team AS INT) BETWEEN 1 AND 10)
GROUP BY T.Team
ORDER BY TeamTotal DESC