Thursday, 4 March 2021

Finding Statistical Mode from 2 String Column of a Different Table using SQL

Lets Assume We have Below Two Tables

Table One 

Table1

ID   | EVENT

1     | Birthday

1     | Marriage

1     | Dance

2     | Birthday

2     | NONE

1     | NONE


Table2

ID   | EVENT

1     | Birthday

1     | Birthday

1     | None

2     | Birthday

2     | NONE

1     | Birthday


Task1 : is to find Mode from both tables for ID='1' Which should result 'Birthday' as this occured 4 times in Both Table.

Task2 : ignore all 'NONE' values

Task3 : if Mode is combination of Multiple Event value than place them as comma separated.


The Query :


select wm_concat(EVENT) as EVENT

FROM (

select  EVENT 

FROM

    (select EVENT , COUNT(EVENT) AS cnt1 from (

 select EVENT from TABLE1  

     Where EVENT!='NONE' AND ID ='1'

UNION ALL

select EVENT  from TABLE2  

     Where EVENT!='NONE' AND ID ='1' GROUP BY  EVENT)

WHERE cnt1 = (SELECT MAX (cnt2) FROM (select COUNT(EVENT) AS cnt2 from (

select EVENT from TABLE1  

    Where EVENT!='NONE' AND ID='1'

UNION ALL

select EVENT  from TABLE2  

    Where EVENT!='NONE' AND ID='1')GROUP BY  EVENT)))) 

No comments:

Post a Comment

  SyntaxError : (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape Solution:...