0

I am new to SQL so this may be a very common/easy question, I want to order these from highest to lowest rather than Team 1, Team 2, Team 3. See below:

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

Right now the result shows like this:

enter image description here

I want it to show highest to lowest rather than by team name. Can this be done with an Order By? I just can't seem to get it to work.

Team 2 - 597, Team 7 - 540, Team 3 - 467, etc.

4

2 回答 2

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
于 2013-07-09T17:41:50.400 回答
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
于 2013-07-09T17:47:12.143 回答