SQL出现次数,摘要查询

时间:2016-05-20 13:26:44

标签: mysql sql

我有一张如下表格,

Product Promotion exists (Y/N)  Week
    A   Y   1
    B   Y   1
    C   Y   1
    A   Y   2
    B   Y   2
    C   N   2
    A   Y   3
    B   Y   3
    C   Y   3
    A   Y   4
    B   Y   4
    C   N   4

我想在总表上看到Promition存在组合输出。像

这样的东西
A, B - 4
B,C  - 2
A,C - 2

因为这只是3个产品看起来很简单..我正在查看数千条记录,并寻找相同的组合,其中总发生次数大于某个数字。如果采用上面的例子,如果该计数是4 ..那么我的输出应该是

A,B - 4

1 个答案:

答案 0 :(得分:1)

试试这个:

SELECT p1, p2, COUNT(*) AS cnt
FROM (
  SELECT t1.Product AS p1, t2.Product AS p2
  FROM mytable AS t1
  JOIN mytable AS t2 
    ON t1.Week = t2.Week AND 
       t1.Product < t2.Product AND 
       t1.Exists = 'Y' AND t2.Exists = 'Y') AS t
  GROUP BY p1, p2     
  ORDER BY cnt DESC

要仅获得超过特定值的对,只需将上面的内容包装在子查询中并添加WHERE cnt >= someValue

Demo here