php - 分组重复值

标签 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>";

最佳答案

你应该像这样使用查询:

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

关于php - 分组重复值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36437940/

相关文章:

mysql - 从第三个相关表中选择数据

mysql - 如何在 MySQL 中构建一个非常简单的博客的表?

c# - Entity Framework - 按同一列中的多个条件选择 - 多对多

mysql - 数据库 - 检索未使用位置的结果

php - 将变量的日期与 MySQL 日期进行比较

javascript - 如何使这种登录/重定向方法更安全

php - php中的隐藏字段

php - 填空优先级列+保持顺序

angularjs - 如何以编程方式打开选择

javascript - 全日历 : Changing Event Background Color