在mysql查询中执行复杂的计算

在mysql查询中执行复杂的计算,mysql,Mysql,我一直在尝试用sql查询进行计算。我有如下的出勤表: roll | sub_id | status abc | 1 | 1 abc | 1 | 0 abc | 2 | 1 xcv | 1 | 1 abc | 2 | 1 abc | 1 | 1 lkj | 2 | 0 这是我的表格主题的一个示例: id | name

我一直在尝试用sql查询进行计算。我有如下的出勤表:

roll   |  sub_id  | status 
abc    |     1    |   1
abc    |     1    |   0
abc    |     2    |   1
xcv    |     1    |   1
abc    |     2    |   1
abc    |     1    |   1
lkj    |     2    |   0
这是我的表格主题的一个示例:

id  |  name 
1   |  Data Structure
2   |  Cloud Computing 
我想为特定卷选择不同的子卷id,然后用0和1统计状态的数量,并链接到主题表并显示它们的名称。 我想要这样的东西:

roll  | sub_id |      name       | status with 0 | status with 1
abc   |   1    |Data Structure   |       1       |      2
abc   |   2    |Cloud Computing  |       0       |      2
有人能给我解释一下吗?
如何处理查询?

您可以在pivot查询中使用条件聚合来获得所需的输出。当值同时为
0
1
时,下面的子查询计算每个
roll
/
子id
组的
状态的计数

SELECT t1.roll,
       t1.sub_id,
       COALESCE(t2.name, 'name is NA'),
       t1.`status with 0`,
       t1.`status with 1`
FROM
(
    SELECT roll,
           sub_id,
           SUM(CASE WHEN status = 0 THEN 1 ELSE 0 END) AS `status with 0`,
           SUM(CASE WHEN status = 1 THEN 1 ELSE 0 END) AS `status with 1`
    FROM attendance
    GROUP BY roll,
             sub_id
) t1
LEFT JOIN
subject t2
    ON t1.sub_id = t2.id
按照下面的链接进行运行演示:


您可以在pivot查询中使用条件聚合来获得所需的输出。当值同时为
0
1
时,下面的子查询计算每个
roll
/
子id
组的
状态的计数

SELECT t1.roll,
       t1.sub_id,
       COALESCE(t2.name, 'name is NA'),
       t1.`status with 0`,
       t1.`status with 1`
FROM
(
    SELECT roll,
           sub_id,
           SUM(CASE WHEN status = 0 THEN 1 ELSE 0 END) AS `status with 0`,
           SUM(CASE WHEN status = 1 THEN 1 ELSE 0 END) AS `status with 1`
    FROM attendance
    GROUP BY roll,
             sub_id
) t1
LEFT JOIN
subject t2
    ON t1.sub_id = t2.id
按照下面的链接进行运行演示:

您可以执行以下操作:

SELECT
  a.roll, 
  a.sub_id, 
  b.name, 
  SUM(Case when status=0 then 1 else 0 end) as 'status with 0',
  SUM(Case when status=1 then 1 else 0 end) as 'status with 1'
FROM
  myTable a inner join subject b on
  a.sub_id = b.id
  group by a.roll, a.sub_id;
我为你做了一把小提琴:

你可以做:

SELECT
  a.roll, 
  a.sub_id, 
  b.name, 
  SUM(Case when status=0 then 1 else 0 end) as 'status with 0',
  SUM(Case when status=1 then 1 else 0 end) as 'status with 1'
FROM
  myTable a inner join subject b on
  a.sub_id = b.id
  group by a.roll, a.sub_id;

我为你做了一个小摆设:

它给出了主题t2附近的语法错误(选择roll,sub_id,这看起来非常复杂。没有更简单的方法吗?@TomCruise这个查询真的没有那么复杂。它给出了主题t2附近的语法错误(选择roll,sub_id,这看起来非常复杂。没有更简单的方法吗?@TomCruise此查询真的没有那么复杂。谢谢!很好的方法。此方法有一个问题:查询正在选择非聚合列(
b.name
),它不会出现在
GROUP BY
子句中,并且可能不会在所有情况下都给出正确的结果。此查询甚至不会在Oracle、SQL Server以及MySQL以外的任何数据库上运行。我同意@TimBiegeleisen。它不会在5.7上开箱即用。此查询有缺陷Hanks!很好的方法。此方法有一个问题:查询正在选择一个非聚合列(
b.name
),该列不会出现在
GROUP BY
子句中,并且可能不会在所有情况下都给出正确的结果。此查询甚至不会在Oracle、SQL Server以及MySQL以外的任何数据库上运行。我同意@TimBiegeleisen。它不会在5.7上开箱即用。此查询有缺陷