sql复杂案例

  工作中往往会遇到非常棘手的数据查询,运营人员不知道你的数据库表是如何设计的,也不知道你的数据库记录了啥数据,他只知道自己需要看什么数据,甚至有些数据根本就不存在.

 

 

  单表查询的难度: 一张数据库的表table,如下图,一个房间两个人对局,房主houser 挑战者challenger,只记录了赢家winner,以及分数point

    

 

  需求,列出  玩家,今天输的总分数,今天赢的总分数,最终输赢的分数最终的查询的结果是

 

 

  暂时不吐槽表的设计者,以及提出需求的运营人员. 要把这个数据查出来,得用很多sql技巧,不限于 case when ,left join ,right join,union

 

  来看一个最简单的查询语句:

  select /*something*/ from table  #从表中查询某字段

 

   根据需求我们可以得出初步sql:

  select player,totallose,totalwin,(totallose+totalwin) from table  #查询玩家输的总数,赢得总数,最终分数,

  显然从table不能直接找到需求的字段,而是要经过一定的逻辑处理和运算

  select player,totallose,totalwin,(totallose+totalwin) from (/*something*/)

  括号里面的(/***/)就是我们需要对数据进行一些逻辑处理

 

  第一步:查询输的,把输的人查出来,以及输的总数

  (select case when winner=houser then challenger when winner=challenger then houser else 0 end AS player, 

  sum(-point) AS lose from table group by player ) AS a

 

  第二步,左联一下,把原本输的人的赢得总数查出来

  LEFT JOIN (SELECT winner AS player ,sum(point) AS win group by player) AS b

  ON a.player=b.player

 

  第三步,把赢的人,和赢的总数查出来,即把刚才的左联变成右连

  (select case when winner=houser then challenger when winner=challenger then houser else 0 end AS player, sum(-point) AS lose from table group by player ) AS a

  RIGHT JOIN (SELECT winner AS player ,sum(point) AS win group by player) AS b

  ON a.player=b.player

 

  第四步 把左联和右连的结果再union一下

 

  回到 我们一开始的最简单的那条查询

  select player,totallose,totalwin,(totallose+totalwin) from (/***/)

 

  最终,我们要把 (/***/) 完成, 把第一二步查出来的结果作为数据从中查出玩家,再union一下右连接

 

SELECT

  a.player AS player , a.lose AS totallose, b.win AS totalwin, (totallose+totalwin) AS total 

FROM

  ( SELECT

    case when winner=houser then challenger when  winner=challenger then houser else 0 end AS player, sum(-point)     AS   lose 

   FROM

    table 

  GROUP BY player

  )  AS

LEFT JION

  (SELECT 

    winner AS player , sum(point) AS win 

  FROM

    table 

  GROUP BY

    player) AS b

ON

  a.player=b.player

UNION

SELECT

  a.player AS player , a.lose AS totallose, b.win AS totalwin, (totallose+totalwin) AS total 

FROM

  ( SELECT

    case when winner=houser then challenger when winner=challenger then houser else 0 end  AS player, sum(-point)     AS   lose 

   FROM

    table 

  GROUP BY player

  )  AS a 

RIGHT JION

  (SELECT 

    winner AS player ,sum(point) AS win 

  FROM

    table 

  GROUP BY

    player) AS b

ON

  a.player=b.player

ORDER BY total DESC

 

本文完......

 

地址:https://mp.weixin.qq.com/s?__biz=MzI4NTEzMjc5Mw==&mid=2650554680&idx=1&sn=4ba6ac9e6e41c17329d5944e5aaaa60d&chksm=f3f833aec48fbab8895402ba2f859064a8c71bda062769a47167360b60bdd21dea6edc8579a1#rd

 

转载于:https://www.cnblogs.com/qq289736032/p/9073718.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值