Domanda

i have the following data

customer_id | text     | i
---------------------------
001         | hi       | 0
001         | all      | 1
002         | do       | 0
002         | not      | 0
003         | copy     | 0

in my query, i group_concat the values of text so i should get results like these

customer_id | text     
---------------------------
001         | hi all
002         | do not
003         | copy

now i only want to group_concat customer_ids if even 1 of records had i set to 1, while i can easily do it when customer_id 001 has both records i value set to 1 when there is only 1 that has been set i get only that

the situation that would lead to the data above being like that is that at first customer 001 only had "hi" however some time later "all" is added so i now want to update the customer with this data

there is a customer table that has the customer ids however i can not set an update flag on the customer id as that table has different data which takes longer to process and the data above is for a separate system

my query looks like this at the time being

SELECT GROUP_CONCAT(text,' ') FROM table
WHERE i = 1
GROUP BY customer_id

what would i need to do in order to get customer_id 001 to return "hi all" when only 1 of the 2 record's i value is 1 while at the same time not getting anything from customer_id's 002 or 003

È stato utile?

Soluzione

You can concat all values, and get the total i value. Then you can filter by this field, knowing that if at least one of the group has a 1 it will appear

selec customer_id, text from
(SELECT customer_id, GROUP_CONCAT(text,' ') as text, sum(i) as total FROM table
WHERE i = 1
GROUP BY customer_id) T
where total > 0

Altri suggerimenti

I'm not sure what you mean by "not getting anything from customers 002 and 003". The following filters them out:

SELECT GROUP_CONCAT(text,' ')
FROM table
GROUP BY customer_id
HAVING max(i) = 1;

you can use EXIST()

SELECT  customer_id, GROUP_CONCAT(text SEPARATOR ' ') result
FROM    tableName a
WHERE   EXISTS
        (
            SELECT  1
            FROM    tableName b
            WHERE   a.customer_id = b.customer_id  AND b.i = 1
        )
GROUP   BY customer_id 
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top