如何编辑这个mssql查询?

时间:2013-09-09 09:44:43

标签: php sql sql-server

我的下面的查询与我的部落排名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的第二条规则。 因此,它将显示Manner和Loyalty点,并按两者排序。

例如,如果战队拥有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

但它根本不显示。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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`