1

我想连接并计算同一列的数据,所以我可以连接但我不能计算重复的数据。

这是我的数据表:

| 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     |

这是我用来连接数据的 sql 查询:

SELECT class AS lesson,
       GROUP_CONCAT( bills ORDER BY bills ) AS bills
FROM tb_presence
GROUP BY class;

下面是我的结果:

| class | bills            |
|-------|------------------|
| 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  |

现在我想计算相等的数据,但继续进行相同的连接。

我想对具有相同值的数据进行“计数”并显示连接(列观察,仅用于帮助理解)

| class | bills | observation                 |
|-------|-------|-----------------------------|
| 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) |

这真的可能吗?

4

1 回答 1

0

这是一个解决方案(感谢@wchiquito for the 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 |
于 2013-11-06T15:13:02.073 回答