0

下面这个查询与我的氏族排名 php 脚本相关联。

SELECT TOP 100 
  IDNum, 
  IDName, 
  Nation, 
  (SELECT SUM(LoyaltyPoint) 
   FROM USERDATA 
   WHERE USERDATA.Knights = KNIGHTS.IDNum 
     AND USERDATA.Authority IN(1, 2)) as ClanLoyalty 
FROM KNIGHTS 
ORDER BY ClanLoyalty DESC

我想为MannerPoint忠诚度添加第二条规则。因此,它将同时显示礼貌点和忠诚点,并按两者排序。

例如,如果氏族有10000忠诚度和100礼仪,那么它的排名会高于20000忠诚度和只有50礼仪的排名。

我尝试了一些但失败了。如果有人愿意帮助我,将不胜感激。

编辑:我试过了: SELECT TOP 100 IDNum, IDName, Nation, (SELECT SUM(LoyaltyPoint) FROM USERDATA WHERE USERDATA.Knights = KNIGHTS.IDNum AND USERDATA.Authority IN(1, 2)) as ClanLoyalty, (SELECT SUM(MannerPoint) FROM USERDATA WHERE USERDATA.Knights = KNIGHTS.IDNum AND USERDATA.Authority IN(1, 2))) as MannerPoint FROM KNIGHTS ORDER BY ClanLoyalty DESC, MannerPoint DESC

但它根本不显示。

4

2 回答 2

0

您可以将两者相加LoyaltyPointMannerPoint使用外部应用:

select top 100
    k.IDNum, 
    k.IDName, 
    k.Nation, 
    u.ClanLoyalty,
    u.ClanManner 
from KNIGHTS as k
    outer apply (
        select
            sum(u.LoyaltyPoint) as ClanLoyalty,
            sum(u.MannerPoint) as ClanManner
        from USERDATA as u
        where u.Knights = k.IDNum and u.Authority in (1, 2)
    ) as u
order by u.ClanManner desc, u.ClanLoyalty desc

或简单的子查询:

select top 100
    k.IDNum, 
    k.IDName, 
    k.Nation, 
    u.ClanLoyalty,
    u.ClanManner
from KNIGHTS as k
    left outer join (
        select
            u.Knights,
            sum(u.LoyaltyPoint) as ClanLoyalty,
            sum(u.MannerPoint) as ClanManner
        from USERDATA as u
        where u.Authority in (1, 2)
        group by u.Knights
    ) as u on u.Knights = k.IDNum
order by u.ClanManner desc, u.ClanLoyalty desc

不知道你想如何排序你的记录,如果你想按 ClanManner 和 ClanLoyalty 的总和排序,你可以这样做:

order by isnull(u.ClanManner, 0) + isnull(u.ClanLoyalty, 0) desc
于 2013-09-09T12:28:35.740 回答
0

这个:

SELECT TOP 100 
IDNum, IDName, Nation, 
    (SELECT SUM(LoyaltyPoint)
     FROM USERDATA 
     WHERE USERDATA.Knights = KNIGHTS.IDNum 
           AND USERDATA.Authority IN(1, 2)) as ClanLoyalty,
    (SELECT SUM(MannerPoint) 
     FROM USERDATA 
     WHERE USERDATA.Knights = KNIGHTS.IDNum 
           AND USERDATA.Authority IN(1, 2))) as MannerPoint 
FROM KNIGHTS 
ORDER BY ClanLoyalty DESC, MannerPoint DESC`

有一个带有额外括号的语法问题,应该是:

SELECT TOP 100 
IDNum, IDName, Nation, 
    (SELECT SUM(LoyaltyPoint)
     FROM USERDATA 
     WHERE USERDATA.Knights = KNIGHTS.IDNum 
           AND USERDATA.Authority IN(1, 2)) as ClanLoyalty,
    (SELECT SUM(MannerPoint) 
     FROM USERDATA 
     WHERE USERDATA.Knights = KNIGHTS.IDNum 
           AND USERDATA.Authority IN(1, 2) ) as MannerPoint 
FROM KNIGHTS 
ORDER BY ClanLoyalty DESC, MannerPoint DESC`
于 2013-09-11T23:23:12.123 回答