组重复值

时间:2016-04-05 22:07:42

标签: php mysql select join group-by

我的下表名为 store_items

id store item qty cost sell date
1  A1     aa   12  5   10   2016-04-06
2  A2     cc   10  6   12   2016-04-06 // Store A2 and A3 have same item 
3  A1     bb   15  5   13   2016-04-01 // Store A1 and A3 have same item
4  A3     bb   10  5   13   2016-04-06
5  A3     cc   22  6   12   2016-04-06
6  A1     dd   17  2   12   2016-04-02
7  A1     ee   10  5   10   2016-04-01

现在我期待输出如下:

Item cost sell A1 A2 A3
aa   5    10   12 0  0
bb   5    13   15 0  10
cc   6    12   0  10 22
dd   2    12   17 0  0
ee   5    10   10 0  0

正如您所看到的,每个项目都显示一次并且其数量列在每个商店的下方,我现在对如何在查询中使用组感到迷茫 代码:

$allstore = $_POST['store']; //Store Name are collected from FORM submit

echo "<table>";
echo "<tr><td align=center>Item Number</td><td align=center>Cost</td><td align=center>Sell</td>";

foreach($allstore as $store => $value){ 
//I've used foreach to find out which store being selected from checkbox form
    echo "<td align=center>".$value."</td>";
}

echo "</tr>";


    $query = "SELECT * from store_items GROUP by item"; //??
    $result = mysql_query($query);

    while($row = mysql_fetch_assoc($result)){

        echo "<tr><td align=center>{$row['item']}</td><td align=center>{$row['cost']}</td><td align=center>{$row['sell']}</td>";

    foreach($allstore as $store => $value){
    echo "<td align=center>".$row['qty']."</td>";
}

    //End of While loop 
    }
echo "</tr>";

1 个答案:

答案 0 :(得分:3)

你应该使用这样的查询:

SELECT Item, cost, sell
, Sum(CASE WHEN store = 'A1' then qty end) A1
, Sum(CASE WHEN store = 'A2' then qty end) A2
, Sum(CASE WHEN store = 'A3' then qty end) A3
FROM store_items 
GROUP BY Item, cost, sell

编辑:
查询数据:

SELECT Item, cost, sell, store, Sum(qty)
FROM store_items 
GROUP BY Item, cost, sell, store 

SELECT Item, cost, sell, Sum(qty)
FROM store_items 
WHERE store = 'A1' --for example
GROUP BY Item, cost, sell