簡體   English   中英

按日期分組,但顯示所有行

[英]Group together by date, but show all rows

通常,當我將東西分組在一起時,顯然是將重復項分組在一起,但是我正在制作一個中獎頁面,其中顯示一堆大獎的中獎者,某些中獎有1名中獎者,而其他有3名中獎,使用GROUP BY date可以只有1位獲勝者,但在應該有3位時只會顯示1位獲勝者。

這是我的代碼

$result = $db->query("SELECT * FROM r_winners GROUP BY date ORDER BY date DESC");
while($rows = $result->fetch_assoc()){
print"<table class='cashout' style='width:100%;'>
<th colspan='3'>".$rows['jackpot_name']." Winners</th>
<tr>
<td style='width:33%;'>".$rows['winner']."</td><td style='width:33%;'>$".$rows['amount']."</td><td style='width:33%;'>".date("m/d/Y", $rows['date'])."</td></tr>
</tr></table>";
}

它打印出這樣的表格

---------------------------------------
Daily     Jackpot     Winners
Username|  $5.00   |  12/5/2012         // This table is right, because there is only 1 winner
---------------------------------------

因為只有1個獲勝者,所以GROUP BY在這里真的沒有影響

這是多位獲獎者的表格

---------------------------------------
Monthly     Jackpot     Winners
Username  |  $5.00   |  12/5/2012         // This table is wrong, because there should be 3 winners
---------------------------------------

它需要看起來像這樣

---------------------------------------
Monthly     Jackpot     Winners
Username  |  $5.00   |  12/5/2012 
Username2 |  $2.00   |  12/5/2012
Username3 |  $1.00   |  12/5/2012        
---------------------------------------

我該怎么做?

編輯:這也許可以解釋這個更好的https://gist.github.com/4221167

只是根本不使用GROUP BY 您已經在使用ORDER BY ,它將把您的日期放入邏輯“分組”中。

為了回應您對將結果輸出到一個表中的評論,這是修改代碼的方法。

$result = $db->query("SELECT * FROM r_winners ORDER BY date DESC");
print "<table class='cashout' style='width:100%;'>";
print "<th colspan='3'>".$rows['jackpot_name']." Winners</th>";
while($rows = $result->fetch_assoc()){
    print "<tr><td style='width:33%;'>".$rows['winner']."</td><td style='width:33%;'>$".$rows['amount']."</td><td style='width:33%;'>".date("m/d/Y", $rows['date'])."</td></tr>";
}
print "</table>";

更改查詢以僅使用ORDER BY並重新格式化循環,將表元素放置在外部,並且僅打印一次標題

$result = $db->query("SELECT * FROM r_winners ORDER BY date DESC");
print"<table class='cashout' style='width:100%;'>";
$jackpot_name = '';
while($rows = $result->fetch_assoc()){
    if ($jackpot_name != $rows['jackpot_name']) {
        $jackpot_name = $rows['jackpot_name'];
        print "<th colspan='3'>".$rows['jackpot_name']." Winners</th>";
    }
    print "<tr><td style='width:33%;'>".$rows['winner']."</td><td style='width:33%;'>$".$rows['amount']."</td><td style='width:33%;'>".date("m/d/Y", $rows['date'])."</td></tr>";
}
print "</table>";

嘗試刪除GROUP BY並僅使用ORDER BY

當然,您應該GROUP BY Monthly ORDER BY Winners ,如果Monthly是唯一的,那么您甚至不需要按GROUP BY

編輯:檢查您的php代碼后,我認為您需要以下內容:

SELECT 
  GROUP_CONCAT(winner_name) AS winner_names,
  SUM(the_value_column_you_want_to_sum) AS amount
FROM r_winners 
GROUP BY date ORDER BY date DESC

暫無
暫無

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

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