使用子查询汇总Mysql表

时间:2019-01-28 01:35:13

标签: mysql sql

我有一个要总结的简单mysql表。这是我的桌子

表名称:hauling_trip

列:

ID, CONTRACTOR, HAULING_SHEET_NO, FROM_LOCATION, TO_LOCATION, LOAD_WEIGHT_KG, PASS_NO

数据:

1   PM  A00001  Stumping A  Pangkalan   940.00  112233
2   PM  A00002  Stumping B  Pangkalan   530.00  112233
3   PM  A00003  Stumping B  Pangkalan   970.00  112244
4   PM  A00004  Stumping A  Pangkalan   450.00  112244
5   TKF A00005  Stumping A  Pangkalan   850.00  112255
6   TKF A00006  Stumping B  Pangkalan   780.00  112255
7   TKF A00007  Stumping A  Pangkalan   903.00  112266

我想做的是,我想通过显示每个PASS_NO的总行程数和负载重量(KG)来汇总此表。这是预期的结果

PASS_NO CONTRACTOR  WEIGHT_A    TRIP_A  WEIGHT_B    TRIP_B
112233  PM          940.00      1       530.00      0
112244  PM          450.00      0       970.00      1
112255  TKF         850.00      1       780.00      0
112266  TKF         903.00      1       0.00        0

相同的PASS_NO表示,牵引单被假定为1次行程。例如,牵引工作表A00001和A00002具有相同的PASS_NO,即112233。因此,这两个牵引工作表都属于1次行程,并且此行程属于FROM_LOCATION装卸站A,因为重量大于装卸站B。

这是我目前正在处理的查询。但是我不知道如何正确地旅行。

SELECT
    a.PASS_NO,
    a.CONTRACTOR,
    ( SELECT sum( LOAD_WEIGHT_KG ) FROM hauling_trip WHERE PASS_NO = a.PASS_NO AND FROM_LOCATION = 'Stumping A' ) AS WEIGTH_A,
    ( SELECT count( PASS_NO ) FROM hauling_trip WHERE PASS_NO = a.PASS_NO AND FROM_LOCATION = 'Stumping A' ) AS TRIP_A,
    ( SELECT sum( LOAD_WEIGHT_KG ) FROM hauling_trip WHERE PASS_NO = a.PASS_NO AND FROM_LOCATION = 'Stumping B' ) AS WEIGHT_B,
    ( SELECT count( PASS_NO ) FROM hauling_trip WHERE PASS_NO = a.PASS_NO AND FROM_LOCATION = 'Stumping B' ) AS TRIP_B, 
    SUM(a.LOAD_WEIGHT_KG) AS TOTAL_WEIGHT
FROM
    hauling_trip AS a 
GROUP BY
    a.PASS_NO, a.CONTRACTOR

1 个答案:

答案 0 :(得分:0)

使用条件聚合:

SELECT ht.PASS_NO, ht.CONTRACTOR,
       sum(case when ht.from_location = 'Stumping A' then ht.load_weight_kg end) as weight_a,
       sum(ht.from_location = 'Stumping A') as trip_a,
       sum(case when ht.from_location = 'Stumping B' then ht.load_weight_kg end) as weight_b,
       sum(ht.from_location = 'Stumping B') as trip_b
       sum(ht.LOAD_WEIGHT_KG) AS TOTAL_WEIGHT
FROM hauling_trip ht
GROUP BY ht.PASS_NO, ht.CONTRACTOR