简体   繁体   中英

PHP - Group multiple sql results with the same ID and get the amount of each

I'm trying to group sql results with the same product_id and count how many of the are there of each

I this photo you can see that I have 4 sales with the same product_id .

id product_id qty price date        user
37         50   1  9.90 2018-09-29     1
31         50   1  9.90 2018-09-29     6
32         50   1  9.90 2018-09-29     6
38         50   1  9.90 2018-09-29     1

Current query:

SELECT
    s.id,
    s.qty,
    s.price
FROM
    sales s
LEFT JOIN products p ON
    s.product_id = p.id
ORDER BY
    s.date
DESC

PHP:

<?php foreach ($sales as $sale):?>
  <tr>
    <td class="text-center"><?php echo count_id();?></td>
    <td><?php echo remove_junk(htmlspecialchars_decode($sale['name'])); ?></td>
    <td class="text-center"><?php echo (int)$sale['qty']; ?></td>
    <td class="text-center"><?php echo remove_junk($sale['price']);?></td>
  </tr>
<?php endforeach;?>

Basically going form a to b like in the photo, without merging them into one row

在此处输入图片说明

Edited to provide a better explanation (Edited again for product_id mistake):

You should use a GROUP statement to group the results by product ID. With a group statement, you can then SUM the value of the quantity column. If you choose you can group by only the product ID, but then the date would be meaningless because all the items with that product ID would be grouped with the date of just one of them. Since you included the date in your result set, it seems that that is an important element of what you're trying to show.

The following code would GROUP BY both product ID and date, which would show you how many of each product were purchased on each date.

SELECT
    s.product_id,
    SUM(s.qty),
    s.price
FROM
    sales s
LEFT JOIN products p ON
    s.product_id = p.id
GROUP BY s.product_id, s.date
ORDER BY
    s.date
DESC

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM