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
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.
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.
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.
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 |
+--------+--------+-----+
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With