using combination of select, union and group by

岁酱吖の 提交于 2019-12-13 07:54:59

问题


I have two similar tables and a third table with one shared column (sms_status_id) with first and second table. I want to select similar columns from first and second table, union them with third table and then remove repetitive rows. This is what I've done so far:

select *
from
(
    select sms_log_id, atm_id, device_id, error_id, datetime, retries, message
    from first_table
    join third_table
    on sms_log_id = sms_status_id
)
union
(
    select sms_id, atm_id, device_id, error_id, datetime, retries, message
    from second_table
    join third_table
    on sms_id = sms_status_id
 )

This gives me what I want but the result has repetitive rows. I tried to use

GROUP BY sms_status_id

but I didn't know where should I put it so didn't work out. Any suggestions??

This is w


回答1:


There is some error in your query.

Please see below code, if this will answer to your question.

@dnoeth is right, UNION always returns distinct rows otherwise use UNION ALL.

mytable1

sms_log_id     | Detail
1                a
1                b
1                c

mytable2

sms_id     | Detail
1            a
2            b
1            d
1            e

mytable3

id     | Status
1        Approve
2        Disapprove

Query:

SELECT t1.sms_log_id as t3_id, t1.Detail, t3.Status
FROM mytable1 as t1
LEFT JOIN mytable3 as t3
  ON t1.sms_log_id = t3.id

UNION

SELECT t2.sms_id as t3_id, t2.Detail, t3.Status
FROM mytable2 as t2
LEFT JOIN mytable3 as t3
  ON t2.sms_id = t3.id

Result:

t3_id   Detail  Status
1       a       Approve
1       b       Approve
1       c       Approve
2       b       Disapprove
1       d       Approve
1       e       Approve

you can't see in the result a from mytable2 because it is already in mytable1, and b is printed because it has different status.

Demo



来源:https://stackoverflow.com/questions/31692678/using-combination-of-select-union-and-group-by

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!