Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sql Query: co-occurrence of column values

Tags:

sql

hive

I have a table like this:

col1     col2
id1      item1
id1      item2
id1      item3
id2      item1
id2      item4
id3      item2
id3      item3

I have to run a query on this table to find the number of times each pair of items shared a common id. For ex, in the above case, the pair (item1, item2) has a count of 1 (only id1 has both item1 and item2). Similarly, the pair (item2, item3) has a count of 2 (id1, id3).

I can write code to achieve this, but I am not able to come with a sql query. Help me write an efficient query to output the following:

col1    col2    count   
item1   item2    1
item1   item3    1
item1   item4    1
item2   item3    2 

Thanks

like image 498
devj Avatar asked Apr 10 '17 11:04

devj


People also ask

Can I use WHERE and count together in SQL?

SQL SELECT COUNT() can be clubbed with SQL WHERE clause. Using the WHERE clause, we have access to restrict the data to be fed to the COUNT() function and SELECT statement through a condition.

Can we use count on multiple columns in SQL?

You can use CASE statement to count two different columns in a single query. To understand the concept, let us first create a table. The query to create a table is as follows. Insert some records in the table using insert command.

Does count work without group by?

Using COUNT, without GROUP BY clause will return a total count of a number of rows present in the table. Adding GROUP BY, we can COUNT total occurrences for each unique value present in the column.


1 Answers

select    t1.col2  as item_A
         ,t2.col2  as item_B
         ,count(*) as cnt

from                mytable t1 
          join      mytable t2
          on        t1.col1 = t2.col1

where     t1.col2 < t2.col2

group by  t1.col2
         ,t2.col2

+--------+--------+-----+
| item_a | item_b | cnt |
+--------+--------+-----+
| item1  | item2  |   1 |
| item1  | item3  |   1 |
| item1  | item4  |   1 |
| item2  | item3  |   2 |
+--------+--------+-----+
like image 122
David דודו Markovitz Avatar answered Oct 03 '22 13:10

David דודו Markovitz