如何连接两个表,其中一些行部分空白?

时间:2017-03-17 20:52:02

标签: sql sybase

从我对问题过于具体的原始问题开始: 我有一个匹配表格式:

ID|Player1|Player2|P1Score|P2Score
--+-------+-------+-------+-------
 1|     71|     83|      2|      0
 2|     73|     71|      1|      1
 3|     71|     65|      2|      0
 4|     65|     83|      0|      2

哪里

  • 2是胜利
  • 1是领带,
  • 0是亏本。

我需要格式化表格:

Player|Wins|Draws|Losses
------+----+-----+------
    71|   2|    1|     0
    73|   0|    1|     0
    83|   1|    0|     1
    65|   0|    0|     1

我并不知道如何去做。

我最接近的是

SELECT Player1, COUNT(P1Score) FROM matches WHERE P1Score = 2 GROUP BY Player1

并重复绘制和丢失,然后加入表格,重复P2,并将值加在一起,但似乎JOIN不是我需要的命令。

2 个答案:

答案 0 :(得分:4)

  

2是胜利,1是平局,0是亏损

鉴于上述每个条件,我们可以使用<?php $dir = __DIR__; require_once("$dir/../PHPMailer-master/PHPMailerAutoload.php"); extract($_POST, EXTR_PREFIX_ALL, "P"); $name = $_POST['postName']; $email = $_POST['postEmail']; $subject = $_POST['postSubject']; $message = $_POST['postMessage']; $file = $_POST['postFile']; echo "Name: ".$_POST['postName']; echo "\n"; echo "Email: ".$_POST['postEmail']; echo "\n"; echo "Subject: ".$_POST['postSubject']; echo "\n"; echo "Message: ".$_POST['postMessage']; echo "\n"; echo "File: ".$_POST['postFile']; $mail = new PHPMailer; $mail->IsSMTP(); // telling the class to use SMTP $mail->Host = "mail.gmail.com"; // SMTP server //$mail->SMTPDebug = 2; // enables SMTP debug information (for testing) $mail->SMTPAuth = true; // enable SMTP authentication $mail->SMTPSecure = "tls"; // sets the prefix to the servier $mail->Host = "smtp.gmail.com"; // sets GMAIL as the SMTP server $mail->Port = 587; // set the SMTP port for the GMAIL server $mail->Username = "xxxx@gmail.com"; // GMAIL username $mail->Password = "xxxx"; // GMAIL password $mail->SetFrom($email, $name); $mail->AddReplyTo($email, $name); $mail->addAddress("xxxx@gmail.com", "name"); $mail->AddAttachment("$file"); $mail->Subject = "$subject"; $mail->Body = "$message"; if(!$mail->send()) { echo 'Message could not be sent.'; echo 'Mailer Error: ' . $mail->ErrorInfo; } else { echo 'Message has been sent'; } ?> 表达式按case计算相应的列。使用score取消数据取消,然后union allsum()汇总数据:

Player

答案 1 :(得分:1)

如果在匹配表中你有SCORE而不是Win,Loss和Draws的数字代码,这应该有效:

SELECT Player, SUM(WIN) AS WINS, SUM(DRAW) AS DRAWS, SUM(LOSS) AS LOSSES 
FROM ( 
 --Create a sub query where each row is how a player did in a given match
 SELECT A.Player, 
   (CASE WHEN (A.Player = B.Player1 AND B.P1Score>B.P2Score)
      OR (A.Player = B.Player2 AND B.P2Score>B.P1Score) THEN 1 ELSE 0 END) WIN,       
   (CASE WHEN (A.Player = B.Player1 AND B.P1Score<B.P2Score)
      OR (A.Player = B.Player2 AND B.P2Score<B.P1Score) THEN 1 ELSE 0 END) LOSS,
   (CASE WHEN B.P1Score=B.P2Score THEN 1 ELSE 0 END) DRAW
 FROM (
  SELECT DISTINCT Player
  FROM (
   SELECT Player1 FROM matches
   UNION ALL
   SELECT Player2 FROM matches
  ) A
 LEFT JOIN matches B
)