简体   繁体   中英

GROUP_CONCAT not working in Sub-Query

I have tried this query to get the following data

SELECT 
  GROUP_CONCAT( sb.p_id ) , 
  TRUNCATE( SUM( sb.total_amount ) , 2 ) grand_total, 
  TRUNCATE( SUM( sb.amount_wot ) , 2 ) sale_amount, 
    (SELECT TRUNCATE( SUM( (item_qty * item_price) * tax_price /100 ) , 2 ) 
      FROM ci_bill_items
        WHERE bill_id IN ( GROUP_CONCAT( sb.p_id ) ) ) tax_amount
FROM ci_suppliers_bills sb
  WHERE sb.p_id >0

I got the expected result but not the tax_amount its return null but if i run the seperate query like :

SELECT TRUNCATE( SUM( (item_qty * item_price) * tax_price /100 ) , 2 ) 
    FROM ci_bill_items
    WHERE bill_id IN ( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 71 ) 

Then i get the correct result. But all i want in one query like the first one, is group_concat not working like i tried bill_id IN ( GROUP_CONCAT( sb.p_id ) ) ? Help is much appriciated.

You can use FIND_IN_SET like this:

SELECT 
  GROUP_CONCAT( sb.p_id ) , 
  TRUNCATE( SUM( sb.total_amount ) , 2 ) grand_total, 
  TRUNCATE( SUM( sb.amount_wot ) , 2 ) sale_amount, 
    (SELECT TRUNCATE( SUM( (item_qty * item_price) * tax_price /100 ) , 2 ) 
      FROM ci_bill_items
        WHERE FIND_IN_SET(bill_id, GROUP_CONCAT( sb.p_id ) ) > 0 ) tax_amount
FROM ci_suppliers_bills sb
  WHERE sb.p_id >0

GROUP_CONCAT doesn't return a list, it returns a string. To get a list that you can use with IN , you need to run a subquery:

WHERE bill_id IN (SELECT p_id FROM ci_suppliers_bills
                  WHERE p_id > 0)

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