我已经规范化我的表以分离beetwen tb_header和tb_detail。 这是tb_repair的详细信息。
mysql> SELECT DETAIL_ID, REPAIR_ESTIMATE_ID, REMARKS, MANHOUR FROM tb_repair_detail;
+-----------+--------------------+----------------------+---------+
| DETAIL_ID | REPAIR_ESTIMATE_ID | REMARKS | MANHOUR |
+-----------+--------------------+----------------------+---------+
| 9 | 50 | Anda | 12.00 |
| 10 | 50 | Jika | 10.00 |
| 11 | 51 | ACRYLIC | 12.00 |
| 12 | 51 | Pembersihan exterior | 10.00 |
| 13 | 51 | Repairing | 10.00 |
+-----------+--------------------+----------------------+---------+
5 rows in set (0.00 sec)
现在,为了让用户更具可读性,现在我想创建一个如下所示的视图:
mysql> SELECT a.REPAIR_ESTIMATE_ID , a.EIR_REF ,
-> (SELECT b.NAMA FROM tb_customer_master b WHERE a.COSTUMER_ID = b.COSTUMER_ID) AS "NAMA_CUSTOMER"
-> from tb_master_repair_estimate a ;
+--------------------+---------+----------------------+
| REPAIR_ESTIMATE_ID | EIR_REF | NAMA_CUSTOMER |
+--------------------+---------+----------------------+
| 50 | 1545053 | APL |
| 51 | 1545052 | APL |
+--------------------+---------+----------------------+
2 rows in set (0.00 sec)
我的问题是,我想把工时总数REPAIR_ESTIMATE_ID
如何将这个工时总数放在这个视图中?我知道查询sum()每个REPAIR ESTIMATE_ID
喜欢
mysql> SELECT SUM(MANHOUR) AS TOTAL FROM tb_repair_detail a WHERE a.REPAIR_ESTIMATE_ID = 51
mysql> SELECT SUM(MANHOUR) AS TOTAL FROM tb_repair_detail a WHERE a.REPAIR_ESTIMATE_ID = 50;
+-------+
| TOTAL |
+-------+
| 22.00 |
+-------+
+-------+
| TOTAL |
+-------+
| 32.00 |
+-------+
1 row in set (0.00 sec)
但是,我如何让他们进入这些观点?
答案 0 :(得分:1)
SELECT a.repair_estimate_id, a.eir_ref, b.nama AS nama_customer, c.total
FROM tb_master_repair_estimate a, tb_customer_master b,
(SELECT repair_estimate_id, SUM(manhour) AS total
FROM tb_repair_detail
GROUP BY repair_estimate_id) c
WHERE a.repair_estimate_id = c.repair_estimate_id
AND a.COSTUMER_ID = b.COSTUMER_ID
我认为,应该给出所需的结果集。使你的视图的查询,你应该设置。
请注意条款GROUP BY repair_estimate_id
,该子句会导致子查询为 SUM(manhour)
的每个不同值计算repair_estimate_id
。