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

时间:2016-08-20 23:21:35

标签: 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 
1   |  Data Structure
2   |  Cloud Computing 

我想为特定的roll选择不同的sub_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

有人可以解释一下吗? 我该如何处理查询?

2 个答案:

答案 0 :(得分:3)

您可以在数据透视查询中使用条件聚合来获取所需的输出。对于每个status / 0组,当1roll的值均为sub_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

请按照以下链接查看正在运行的演示:

SQLFiddle

答案 1 :(得分:0)

你可以这样做:

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;

我为你做了一个小提琴:http://sqlfiddle.com/#!9/23d1d9/11/0