简体   繁体   中英

How do I fix this SQL query (MariaDB) to produce the correct output?

I have been trying to extract some data from a database and produce the correct output. The following is what I am looking for

id | ref_no | Order time | discount code | total | items | donations

This is my SQL query so far:

SELECT 
  order.id, 
  order.ref_no, 
  order.cdate AS "Order time", 
  order.promocode AS "discount code", 
  order.orig_total as "total", 
  GROUP_CONCAT(order_item_ref.item_id ORDER BY order_item_ref.item_id) AS "items", 
  (CASE WHEN order_item_ref.item_id = "99" 
   THEN order_item_ref.quantity ELSE "0" END) AS "donations" 
FROM `order` 
INNER JOIN `order_item_ref` 
ON order.id = order_item_ref.order_id 
WHERE order.deleted = "0" 
GROUP BY order.id;

Currently it doesn't quite work. The donation column is supposed to show 0 when an order does not contain an item with the item number 99 or the actual amount (order_item_ref.quantity) if it does. However the query only works sometimes to produce something like the following:

实际屏幕帽

If I drop by the GROUP BY and GROUP CAT parts the query works as intended, however I need to keep the grouping intact.

How can I fix the query so the output is correct?

Edit: the output for line 48 is correct. The output for line 49 is not. There should be a non-zero number for the right hand column which should come from order_item_ref.quantity as per the SQL query above.

Since the question has been reopened I can post my own answer. After the explanation made by KIKO Software, I was looking for a way to aggregate (CASE WHEN order_item_ref.item_id = "99" THEN order_item_ref.quantity ELSE "0" END) AS "donations" and found that I was able to do it by simply summing over the output like so:

SUM((CASE WHEN order_item_ref.item_id = "99" THEN order_item_ref.quantity ELSE "0" END)) AS "donations"

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