【问题标题】:Count min and max from a field从字段中计算最小值和最大值
【发布时间】:2015-12-03 08:01:05
【问题描述】:

我有这样的表 1:

number     p     uc_id     date
3         1        g        24/09/2015
4         0        g        24/09/2015
5         1        g        24/09/2015
5         1        f        25/09/2015
3         0        f        25/09/2015
5         1        g        26/09/2015

还有一个表 2:

id       name
g        Magic
f        Blue

我希望 sql 查询返回类似的东西

name      min     max
Magic     1       2
Blue      1       1

我的查询我已经完成了类似日期的操作,但我无法检索最小值和最大值

Select 
    p.date, 
    uc.name, 
    min((Select 
         uc.name, 
         count(p.p) 
         from table1 p, table2 uc 
         where p.p = 1 and uc.id = p.uc_id 
         group by uc.name, p.date)) as 'Min', 
    max((Select uc.name, 
         count(p.p) 
         from table1 p, table2 uc 
         where p.p=1 and uc.id = p.uc_id 
         group by uc.name, p.date)) as 'Max' 
From table1 p, table2 uc
Where uc.id = p.uc_id
group by uc.name

我想计算 p=1 的列 p 并按日期对它们进行分组,对于每个日期我想检索之前完成的计数的最小值和最大值。还在另一个表中显示名称。

【问题讨论】:

  • 你的返回查询逻辑是什么,最小值/最大值是多少?
  • Min when p=0 and Max when p=1????为什么魔法的最大值是 2 而不是 3??
  • 一个错误是您在inner selectouter select 中使用别名p
  • 基本上我想从 p 中检索最大值和最小值 ...但只计算 p=1 我想在一个日期中查看的日期计算每天有多少个 1 并告诉最小值和最大的
  • 请阅读How to ask

标签: mysql sql


【解决方案1】:

SQL FIDDLE DEMO

使用按日期的总计数名称创建子查询。

SELECT name, min(nCount) cMin, max(nCount) cMax
FROM (Select 
          uc.name,
          p.date, 
          count(p) as nCount
      From table1 p, table2 uc
      Where uc.id = p.uc_id
      and   p = 1 
      group by uc.name, p.date) nameCount
GROUP BY name

【讨论】:

  • 我使用 MS SQL 2014,如果您有不同的 RDBMS,请告诉我。在小提琴中,您可以选择nameCount 中的文本以查看部分结果。
  • 我正在使用 mysql,但那里不支持它......但是是的,这就是我需要的
  • 我更新到 MySql。请记住下次在您的问题中包含该信息。
  • 谢谢它:D Muchas Gracias!
猜你喜欢
  • 1970-01-01
  • 2020-12-23
  • 1970-01-01
  • 2015-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多