我一直试图让这个工作,但有些东西让我绊倒了。我在 SO 上搜索,但没有找到任何描述我的具体案例的主题。我有以下架构
在这里小提琴:http ://www.sqlfiddle.com/#!2/ac8162/6
表records
:
| ID | CONTRACT | NAME | STATUS |
|----|----------|----------|---------|
| 1 | US | FOO | status1 |
| 2 | US | BAR | status1 |
| 3 | UK | ABC Inc. | status3 |
| 4 | PL | EFG LTD. | status2 |
| 5 | UK | XXX Inc. | status2 |
|----|----------|----------|---------|
表transactions
:
| ID | RECORD_ID | RESPONSE_DELAY | STATUS |
|----|-----------|----------------|---------|
| 1 | 1 | 8889 | status1 |
| 2 | 1 | 8813 | status1 |
| 3 | 1 | 5908 | status2 |
| 4 | 1 | 4779 | status3 |
| 5 | 2 | 519 | status1 |
| 6 | 2 | 8804 | status1 |
| 7 | 3 | 2604 | status1 |
| 8 | 3 | 5054 | status2 |
| 9 | 3 | 385 | status3 |
| 10 | 4 | 8852 | status1 |
| 11 | 4 | 4330 | status1 |
| 12 | 4 | 4507 | status1 |
| 13 | 4 | 6282 | status2 |
| 14 | 4 | 5789 | status3 |
| 15 | 4 | 8685 | status4 |
| 16 | 5 | 8339 | status1 |
| 17 | 5 | 9543 | status1 |
| 18 | 1 | 7870 | status1 |
|----|-----------|----------------|---------|
records
与 有一对多的关系transactions
。我正在尝试从中获取按合同分组的报告。我正在使用以下查询:
SELECT
t0.`contract` as contract,
COUNT(DISTINCT t0.`id`) as rec_num,
COUNT(t1.`id`) as tr_num,
AVG(t1.`response_delay`) as rd_avg,
SUM(CASE WHEN t0.`status`='status1' THEN 1 ELSE 0 END) as s1,
SUM(CASE WHEN t0.`status`='status2' THEN 1 ELSE 0 END) as s2,
SUM(CASE WHEN t0.`status`='status3' THEN 1 ELSE 0 END) as s3
FROM
records as t0
LEFT JOIN transactions AS t1
ON
(t0.id = t1.record_id)
GROUP BY contract ORDER BY t0.`id` DESC
结果:
| CONTRACT | REC_NUM | TR_NUM | RD_AVG | S1 | S2 | S3 |
|----------|---------|--------|-----------|----|----|----|
| PL | 1 | 6 | 6407.5 | 0 | 6 | 0 |
| UK | 2 | 5 | 5185 | 0 | 2 | 3 |
| US | 2 | 7 | 6511.7143 | 7 | 0 | 0 |
|----------|---------|--------|-----------|----|----|----|
我的目标是计算每个合同的每种状态类型,只计算记录状态而不是交易状态,我追求的结果是:
| CONTRACT | REC_NUM | TR_NUM | RD_AVG | S1 | S2 | S3 |
|----------|---------|--------|-----------|----|----|----|
| PL | 1 | 6 | 6407.5 | 0 | 1 | 0 |
| UK | 2 | 5 | 5185 | 0 | 1 | 1 |
| US | 2 | 7 | 6511.7143 | 2 | 0 | 0 |
|----------|---------|--------|-----------|----|----|----|
任何帮助是极大的赞赏