我无法从sql中的计数值获得最大值

时间:2016-10-23 16:40:19

标签: mysql sql

我有两个表。表t1有列(ID,Name),t2有列(ID,Date,Time)...我想运行像

这样的查询
select t1.Name,t2.ID,count(t2.Date)as Present_Days,MAX(x) as total 
FROM (SELECT COUNT(t2.ID) AS x FROM t2 GROUP BY ID) as y 
from t1 
INNER JOIN t2 on t1.ID=t2.ID 
group by Name

当我将此行“MAX(x)作为总FROM(SELECT COUNT(t2.ID)AS x FROM t2 GROUP BY ID)删除为y”来自查询时,它会给出结果..但原始查询不起作用...运行此查询可以做些什么。

1 个答案:

答案 0 :(得分:0)

错误的FROM()dinamic表和两个FROM而不是一个正确的内连接可能是你正在寻找这样的东西

  select 
       t1.Name
      ,t2.ID
      ,count(t2.Date) as Present_Days
      ,MAX(y.x) as total 
  FROM ( 
          SELECT t2.ID, COUNT(t2.ID) AS x 
          FROM t2 
          GROUP BY ID
        )  y 
  INNER  JOIN  t1 on y.ID = t1.ID
  INNER JOIN t2 on t1.ID=t2.ID 
  group by t1.Name, t2.ID

如果您需要从t2开始命名时间的另一列,则可以使用

  select 
       t1.Name
      ,t2.ID
      ,count(t2.Date) as Present_Days
      ,MAX(y.x) as total 
      , t2.`time`
  FROM ( 
          SELECT t2.ID, COUNT(t2.ID) AS x 
          FROM t2 
          GROUP BY ID
        )  y 
  INNER  JOIN  t1 on y.ID = t1.ID
  INNER JOIN t2 on t1.ID=t2.ID 
  group by t1.Name, t2.ID, t2.`time`

你加入表t2的事实你可以直接在主选择中选择t2.time ..

无论如何,您也可以从子选择中选择t2.time并在子查询中正确添加此列,并在下面的示例中使用正确的别名,例如列my_time

  select 
       t1.Name
      ,t2.ID
      ,count(t2.Date) as Present_Days
      ,MAX(y.x) as total 
      , y.my_time
  FROM ( 
          SELECT t2.ID, t2.`time` as my_time, COUNT(t2.ID) AS x 
          FROM t2 
          GROUP BY ID
        )  y 
  INNER  JOIN  t1 on y.ID = t1.ID
  INNER JOIN t2 on t1.ID=t2.ID 
  group by t1.Name, t2.ID, t2.`time`

对于absent_days,您可以使用所涉及的两列之间的差异(无别名)

  select 
       t1.Name
      ,t2.ID
      ,count(t2.Date) as Present_Days
      ,MAX(y.x) as total 
      , t2.`time`
      , MAX(y.x) - count(t2.Date) as Absent_Days
  FROM ( 
          SELECT t2.ID, COUNT(t2.ID) AS x 
          FROM t2 
          GROUP BY ID
        )  y 
  INNER  JOIN  t1 on y.ID = t1.ID
  INNER JOIN t2 on t1.ID=t2.ID 
  group by t1.Name, t2.ID, t2.`time`

如果您需要按名称过滤,可以

  select 
       t1.Name
      ,t2.ID
      ,count(t2.Date) as Present_Days
      ,MAX(y.x) as total 
      , t2.`time`
      , MAX(y.x) - count(t2.Date) as Absent_Days
  FROM ( 
          SELECT t2.ID, COUNT(t2.ID) AS x 
          FROM t2 
          GROUP BY ID
        )  y 
  INNER  JOIN  t1 on y.ID = t1.ID
  INNER JOIN t2 on t1.ID=t2.ID 
  where   t1.Name =  'somename' 
  group by t1.Name, t2.ID, t2.`time`