簡體   English   中英

根據同一個表中的兩列選擇單列的總和

[英]Selecting sum of single column depending on two columns on same table

我有一個非常類似於下面的表。 表中的p1p2指的是另一個表上的播放器的id。

id score p1 p2 date
-- ----- -- -- ----
1  12    1  2  2011.10.21
2  23    3  4  2011.10.22
3  21    1  3  2011.10.23
4  35    5  1  2011.10.24
5  11    2  3  2011.10.25

我想要做的是獲得得分最高的玩家ID(p1或p2)。 我的解決方案類似於select sum(score)但我無法形成查詢,因為玩家可能同時出現在p1或p2列中。

另外一個更大的問題是當我想要從最高到最低分數。 我不知道該怎么辦。 如果我需要分組以分隔列,我如何對分數求和? 我想要的結果與此輸出類似:

pID score times_played
--- ----- ------------
1   68    3
3   55    3
5   35    1
2   23    2
4   23    1

我的數據庫設計有缺陷嗎? 如果有一種更聰明的方式我想知道。 我應該需要單獨的單個查詢,以便我可以在PHP或其他東西上合並它們嗎?

任何幫助,將不勝感激。 干杯。

PS:我想不出一個好主題。 隨意編輯。

您可以將玩家放在一列中:

select id, score, p1 as player, date from yourtable
union all
select id, score, p2 as player, date from yourtable

你現在有一個列中的玩家。 您可以這樣做以獲得所有玩家的得分總和

select sum(score), player from (
    select id, score, p1 as player, date from yourtable
    union all
    select id, score, p2 as player, date from yourtable
) group by player

現在,你說你也想知道玩家玩了多少次並按降序排序:

select sum(score), player, count(*) as timesPlayed from (
    select id, score, p1 as player, date from yourtable
    union all
    select id, score, p2 as player, date from yourtable
) group by player order by sum(score) desc

試試這個讓玩家得分最高(無視領帶)

select id,p1,p2 
from table t1
join (select max(score) as MaxS) xx on xx.MaxS = t1.Score
limit 1

要獲得玩家總分,請嘗試此操作

select Player as pID,Sum(tot) as Score, count(*) as TimesPlayed
from
(
select p1 as Player,sum(score) as Tot
from table 
group by p1
union all
select p2,sum(score)
from table 
group by p2
) xx
Group by xx.Player
order by Score desc

或者在表上使用UNION(ALL),您可以嘗試這樣的方法:

SELECT
  CASE p.PlayerNumber WHEN 1 THEN t.p1 ELSE t.p2 END AS pID,
  SUM(t.score) AS score,
  COUNT(*) AS times_played
FROM atable t
  CROSS JOIN (SELECT 1 AS PlayerNumber UNION ALL SELECT 2) p
GROUP BY
  pID /* this is probably MySQL-specific; most, if not all, other major
database systems would require repeating the entire pID expression here, i.e.
GROUP BY
  CASE p.PlayerNumber WHEN 1 THEN t.p1 ELSE t.p2 END
*/
ORDER BY
  score DESC,
  times_played DESC  /* this is based on your result set;
                        you might want to omit it or change it to ASC */

更新 ,在回答評論中的問題時:將結果集加入user表:

SELECT
  `user`.*,  /* you should probably specify
                the necessary columns explicitly */
  totals.score,
  totals.times_played
FROM `user` u
  INNER JOIN (
    SELECT
      CASE p.PlayerNumber WHEN 1 THEN t.p1 ELSE t.p2 END AS pID,
      SUM(t.score) AS score,
      COUNT(*) AS times_played
    FROM atable t
      CROSS JOIN (SELECT 1 AS PlayerNumber UNION ALL SELECT 2) p
    GROUP BY
      pID
  ) totals ON user.id = totals.pID
ORDER BY
  totals.score DESC,
  totals.times_played DESC

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM