我想连接和计算同一列的数据,所以我可以连接但我不能计算重复的数据。见下表
ID bills class
1 0.5 2
2 1 1
3 0.5 2
5 1 3
6 0 2
7 0.5 1
8 1 2
9 1 3
10 0.5 1
11 0 2
12 1 1
13 0 3
14 1 2
15 0 1
16 0 1
17 0.5 3
18 0 3
13 0.5 3
下面的mysql查询我用来连接数据
SELECT class AS lesson,
GROUP_CONCAT( bills ORDER BY bills ) AS bills
FROM tb_presence
GROUP BY class;
结果如下
类账单
1 1,0.5,0.5,1,0,0
2 0.5,0,1,0,1
3 1,1,0,0.5,0,0.5
现在我想计算相同的数据,但继续使用相同的连接。
我想用相同的值“计算”数据并显示连接(列观察,只是为了帮助理解)
班级议案观察
1 2,2,2(2 = 0 + 0)(2 = 0.5 + 0.5)(2 = 1 + 1)
2 2,1,2(2 = 0 + 0)(1 = 0.5)(2 = 1 + 1)
3 2,2,2(2 = 0 + 0)(2 = 0.5 + 0.5)(2 = 1 + 1)
这真的有可能吗?
答案 0 :(得分:0)
这是一个解决方案(感谢@wchiquito for sqlfiddle)请参阅http://sqlfiddle.com/#!2/2d2c8/1
正如您所看到的,它无法动态确定账单的价值并计算它们。但是你需要每个账单价值计数。
SELECT class AS lesson,
GROUP_CONCAT( bills ORDER BY bills ) AS bills
,SUM(IF(bills=0,1,0)) AS Count0
,SUM(IF(bills=0.5,1,0)) AS Count05
,SUM(IF(bills=1,1,0)) AS Count1
,COUNT(*) AS totalRecords
,COUNT(*)
- SUM(IF(bills=0,1,0))
- SUM(IF(bills=0.5,1,0))
- SUM(IF(bills=1,1,0))
AS Missing
FROM tb_presence GROUP BY class;
我添加了一条额外的记录,以显示如果您没有考虑所有值,“缺失”列可能会显示。
结果
| LESSON | BILLS | COUNT0 | COUNT05 | COUNT1 | TOTALRECORDS | MISSING |
|--------|-----------------------------------------|--------|---------|--------|--------------|---------|
| 1 | 0.00,0.00,0.50,0.50,1.00,1.00,1.00,4.00 | 2 | 2 | 3 | 8 | 1 |
| 2 | 0.00,0.00,0.50,0.50,1.00,1.00 | 2 | 2 | 2 | 6 | 0 |
| 3 | 0.00,0.00,0.50,0.50,1.00,1.00 | 2 | 2 | 2 | 6 | 0 |