简体   繁体   中英

mysql combining two tables to produce the following output

hello i had ask the same question before but i want another way. we can use locate and max function to solve the question. but my teacher told me to do like this

  1. my code is like this when '0' then '1' else '0'

      select u.id, u.name, case f.finger when '0' then '1' else '0' end as '0', case f.finger when '1' then '1' else '0' end as '1', case f.finger when '2' then '1' else '0' end as '2', case f.finger when '3' then '1' else '0' end as '3', case f.finger when '4' then '1' else '0' end as '4', case f.finger when '5' then '1' else '0' end as '5' from users u left join user_fingerprints f on u.id= f.user_id 

    the code above will resulted in 8 rows.

  2. then i need to combine the rows so that the rows with the same id combine to produce this

  3. from that result then use case function. when the value is 1 then y. when value is zero then n.

can someone give me the answer without the use of max function? thanks
the table and result 在此输入图像描述

You can also do it with SUM() and another CASE EXPRESSION :

SELECT t.id,t.name,
       CASE WHEN t.`0` > 0 THEN 'Y' ELSE 'N' as `0`
       CASE WHEN t.`1` > 0 THEN 'Y' ELSE 'N' as `1`
       ....
FROM (
    SELECT u.id,u.name, 
           SUM(CASE WHEN f.finger = '0' then '1' else '0' end) as `0`,
           SUM(CASE WHEN f.finger = '1' then '1' else '0' end) as `1`,
           ....
    from users u left join user_fingerprints f
     on u.id= f.user_id
    GROUP BY u.id,u.name) t

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