如何从MySQL中的两个表中获取数据并计算每一个?

时间:2016-11-13 09:05:22

标签: mysql

如何在一个查询中写这个?

我有两个表喜欢这个叫做(已故):

id     name     S_id
1       A         6
2       A         6
3       B         5
4       C         8
5       A         6
6       A         6
7       C         8
8       C         8

另一个喜欢这个叫做(缺席):

id     name     S_id
1       A         6
2       A         6
3       A         6
4       A         6
5       A         6
6       A         6
7       B         5
8       c         8

我希望结果如下表所示:

其中(计数延迟)计算迟到的时间和(计数不存在)计算缺席时间。

name    Count late    Count absent
 A          4              6
 B          1              1
 C          3              1

我试过这样的事情:

这没有用!

SELECT 
*
FROM
(SELECT name, COUNT(*) AS '# count absent' FROM absent GROUP BY s_id)  t1 
INNER JOIN
(SELECT name, COUNT(*) AS '# count Late' FROM late   GROUP BY s_id)  t2
ON t1.s_id = t2.s_id ;

5 个答案:

答案 0 :(得分:1)

使用两个表的联合:lates和absents ...然后总结lates和absents的数量。

试试这个:

SELECT 
    SUM(tardies) as 'total_lates', SUM(absences) as 'total_absences', name, s_id
FROM
    ((SELECT
        COUNT(*) as 'tardies',
        0 as 'absences',
        name,
        s_id
    FROM 
        lates
    GROUP BY
        s_id
    )
UNION
    (SELECT 
        0 as 'tardies',
        COUNT(*) as 'absences',
        name,
        s_id
     FROM
        absents
     GROUP BY
        s_id
    )
)
as maintable
GROUP by s_id
ORDER BY name

答案 1 :(得分:0)

如果您需要加入s_id,则必须在子选择中选择这些列

  SELECT 
  *
  FROM
  (SELECT s_id, name, COUNT(*) AS '# count absent' 
      FROM absent GROUP BY s_id)  t1 
  LEFT JOIN
  (SELECTs_id,  name, COUNT(*) AS '# count Late' 
      FROM late   GROUP BY s_id)  t2
  ON t1.s_id = t2.s_id ;

否则生成的选择无法加入,因为没有此

的列

答案 2 :(得分:0)

您需要在此处进行完全外部联接,以确保您保留迟到或不在的人,但不能同时保留两者。好吧,MySQL没有内置的完全外连接支持,但它可以模拟:

SELECT t1.name,
       t2.late_cnt,
       t1.absent_cnt
FROM
(SELECT s_id, name, COUNT(*) AS absent_cnt
  FROM absent GROUP BY s_id, name) t1
LEFT JOIN
(SELECT s_id, name, COUNT(*) AS late_cnt
  FROM late GROUP BY s_id, name) t2
    ON t1.s_id = t2.s_id
UNION
SELECT t1.name,
       t2.late_cnt,
       t1.absent_cnt
FROM 
(SELECT s_id, name, COUNT(*) AS absent_cnt
 FROM absent GROUP BY s_id, name) t1
RIGHT JOIN
(SELECT s_id, name, COUNT(*) AS late_cnt
 FROM late GROUP BY s_id, name) t2
    ON t1.s_id = t2.s_id

答案 3 :(得分:0)

SELECT 
  (case when t1.name is not null then t1.name else t2.name end) as name,t1.absent,t2.late
  FROM
  (SELECT name, COUNT(*) AS 'absent' 
      FROM absent GROUP BY name)  t1 
  FULL JOIN
  (SELECT  name, COUNT(*) AS 'late' 
      FROM late   GROUP BY name)  t2
  ON t1.name = t2.name ;

试试这个。我没试过。希望它有效。

答案 4 :(得分:0)

请尝试以下。它对我有用。

select 
   coalesce( t1.name,t2.name) name,coalesce( t1.late,0) ,coalesce(t2.[absent],0) 
   from 
      (select name,s_id, count(*) as 'late' from late group by s_id,name ) t1 
   FULL OUTER JOIN
      (select name,s_id, count(*) as 'absent' from [absent] group by s_id,name ) 
   t2 on t1.s_id = t2.s_id 
   order by name