sql得到几个元素

时间:2015-11-22 16:50:04

标签: mysql sql sql-server math

我有以下sql表:

| ID | numbers                     |
|----|-----------------------------|
|  1 | 1,3,19,23,28,32,39,42,60,80 |
|  2 | 1,3,18,24,29,33,40,43,61,80 |
|  3 | 1,2,3,25,30,34,41,44,62,78  |

在Numbers中我有一个包含10个数字的字符串。

我想在SQL Server或MySQL中获得所有两个元素(如果有可能是三个,四个等)。

例如,对于两个元素:

  • 所有行中的1,3个上诉(3次)
  • 1,80出现在第一行和第二行(2次)

我试图从每一行中拆分数字并插入一个临时表,然后在生成10的组合后选择k(其中k是一对中的元素数)但是某些东西不起作用。我不知道这是不是最好的主意。

我的代码:http://pastebin.com/qRjPdfay

由于

1 个答案:

答案 0 :(得分:1)

是的,将您的数字库存分成行会使事情变得更容易。如果您使用的是MySQL,可以使用如下查询:

CREATE TABLE mytable2 AS
SELECT
  ID, SUBSTRING_INDEX(SUBSTRING_INDEX(numbers, ',', n),',',-1) AS number
FROM
  mytable CROSS JOIN (SELECT 1 AS n
                      UNION ALL SELECT 2 AS n
                      UNION ALL SELECT 3 AS n
                      UNION ALL SELECT 4 AS n
                      UNION ALL SELECT 5 AS n
                      UNION ALL SELECT 6 AS n
                      UNION ALL SELECT 7 AS n
                      UNION ALL SELECT 8 AS n
                      UNION ALL SELECT 9 AS n
                      UNION ALL SELECT 10 AS n) d;

(如果所有数字都包含正好10个数字,那么这将有效,如果此查询需要一些改进则更少)。然后你可以计算每个数字出现的时间:

SELECT number, COUNT(*) as appears
FROM mytable2
GROUP BY number
ORDER BY appears DESC

您可以根据它们出现的次数对组号进行分组:

SELECT
  appears, GROUP_CONCAT(number) AS numbers
FROM (
    SELECT number, COUNT(*) as appears
    FROM mytable2
    GROUP BY number
    ORDER BY appears DESC
  ) g
GROUP BY
  appears
ORDER BY
  appears DESC

(仅限MySQL),结果如下:

| appears | numbers       |
|---------|---------------|
|       3 | 3,1           |
|       2 | 80            |
|       1 | 43,23,40..... |

请查看小提琴here