sql彩票查询

cqoc49vn  于 2021-07-24  发布在  Java
关注(0)|答案(2)|浏览(306)

我有一个7列的简单表

Week ¦ 1st ¦ 2nd ¦ 3rd ¦ 4th ¦ 5th ¦ 6th ¦

每周,我父亲都会在我创建的一个简单php脚本中添加星期六英国彩票号码。他有早发性老年痴呆症,并试图保持他的大脑活跃。今晚他问了我一个关于数据库的问题。他问我是否有可能看到6个最流行的数字。
我尝试创建一个简单的sql查询:

SELECT 1st, 2nd, 3rd, 4th, 5th, 6th, COUNT(*) AS 'foo' FROM `dad` GROUP BY 1st, 2nd, 3rd, 4th, 5th, 6th ORDER BY foo DESC

但结果并不像我预期的那样。

1st 2nd 3rd 4th 5th 6th foo
2   6   8   32  33  35  1
3   6   12  17  35  40  1
3   6   31  43  46  53  1
etc

我所希望的是将表合并到一列中,然后进行计数并得到一个简单的结果,例如:

Number   Count
2        1
3        2
6        3
8        1

然后按升序排列。然后我可以使用这个sql查询为他创建一个简单的表来显示最常见的数字。
我正在考虑做一个通用的sql查询

SELECT 1st FROM `dad`

然后用结果创建一个数组,然后添加

SELECT 2nd FROM `dad`

到数组的末尾,继续计算所有6列,然后使用php分别计算数字。
有没有更快的办法?

bsxbgnwa

bsxbgnwa1#

你可以做:

select
  n, cnt
from (
  select
    n,
    count(*) as cnt
  from (
    select `1st` as n from `dad` union all
    select `2nd` from `dad` union all
    select `3rd` from `dad` union all  
    select `4th` from `dad` union all
    select `5th` from `dad` union all
    select `6th` from `dad`
  ) x
  group by n
) y
order by cnt desc
limit 6
7hiiyaii

7hiiyaii2#

您的第一项工作应该是修复数据模型。每个数字应存储在单独的行而不是列中,如:

week    pos    num
   1      1      6
   1      2      8
   1      3     32

那么您的查询将是一个简单的聚合查询:

select num, count(*) no_picks from dad group by num order by no_picks desc

对于给定的表结构,您需要取消将列拆分为行。在mysql中,您可以使用 union all 为此:

select num, count(*) no_picks
from (
    select `1st` num from dad
    union all select `2nd` from dad
    union all select `3rd` from dad
    union all select `4th` from dad
    union all select `5th` from dad
    union all select `6th` from dad
) t
group by num 
order by no_picks

相关问题