S
S
sbh2020-05-05 16:33:13
MySQL
sbh, 2020-05-05 16:33:13

How to merge two tables excluding extra records?

Table1

ID    ClientName   StartTS                              FinishTS                    ClientID      
1     Peter        2020-05-01 12:02:01                  2020-05-01 13:02:03         1132
2     Peter        2020-05-01 12:02:01                  2020-05-01 14:02:03         1132
3     Paul         2020-05-01 12:02:01                  2020-05-01 11:01:11         3211
4     Peter        2020-05-02 08:02:11                  2020-05-02 09:01:11         1132
5     Peter        2020-05-02 08:02:11                  2020-05-02 10:01:12         1132
6     Paul         2020-05-01 10:01:32                  2020-05-01 12:01:11         3211
7     Sandra       2020-05-01 12:05:14                  2020-05-01 13:05:14         3333
8     Sandra       2020-05-01 12:05:14                  2020-05-01 14:05:14         3333


Table2
ID   ClientID     Query      DateTime
1    1132         Data1      2020-05-02 10:01:14
2    3211         Data2      2020-05-02 10:01:15
3    1132         Data4      2020-05-02 10:01:33
4    3211         Data4      2020-05-02 10:01:37


It is necessary to search by Table2.Query = Data4 as a result, get a table of the form
ClientName, count(ClientName)

I tried to do RightJoin but the rows are duplicates due to the fact that in Table1 session 1 is the same duplicate (the beginning is the same and the end is shifted )
In the result table, the counters must add up to 2, because there are only 2 rows in Table2 with the entry Query = Data4

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim, 2020-05-05
@MaximaXXl

I didn’t understand something in the formulation of what is needed, but it looks like you need something like this:

select ClientName, count( ClientName) cnt_all_row, count( distinct ClientName) cnt_unique_CN
from table2 t2
join table1 t1 on (t1.ClientID = t2.ClientID)
where t2.Query = 'Data4'
group by ClientName

or something like that
select t2.Query, count( distinct ClientName) cnt_unique_CN
from table2 t2
join table1 t1 on (t1.ClientID = t2.ClientID)
where t2.Query = 'Data4'
group by t2.Query

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question