DB2我需要组合两个查询,并且两个查询都按同一列进行分组

时间:2015-01-30 17:56:18

标签: sql db2

我在组合这两个查询时遇到了问题。

SELECT  d1.DRIVER_ID, SUM(LOADED_MILES)+SUM(EMPTY_MILES) AS Miles
FROM DRIVERPAY 
    WHERE LEG_DATE >= '2013-10-05'
AND LEG_DATE < '2013-12-29'
AND PAY_DESCRIPTION = 'Paid by Mileage'
AND PMT_STATE = 'X'
GROUP BY d1.DRIVER_ID

SELECT  DRIVER_ID, SUM(HOURS) 
FROM DRIVERPAY 
WHERE LEG_DATE >= '2013-10-05'
AND LEG_DATE < '2013-12-29' 
AND PAY_CODE = 'P_HOURLY' 
AND PAID = 'True' 
GROUP BY DRIVER_ID

我曾尝试使用完整的外连接,但我希望一列中的Driver_ID不是两列。

SELECT DriverMiles.Driver_ID, DriverHours.Driver_ID, DriverMiles.Miles,
DriverHours.Hours
FROM
(
SELECT  d1.DRIVER_ID, SUM(LOADED_MILES)+SUM(EMPTY_MILES) AS Miles
FROM DRIVERPAY AS D1
WHERE LEG_DATE >= '2013-10-05'
AND LEG_DATE < '2013-12-29'
AND PAY_DESCRIPTION = 'Paid by Mileage'
AND PMT_STATE = 'X'
AND  PAID = 'True'
GROUP BY D1.DRIVER_ID
) AS DriverMiles
FULL OUTER JOIN
(
SELECT  d2.DRIVER_ID, SUM(HOURS) AS Hours
FROM DRIVERPAY AS d2
WHERE LEG_DATE >= '2013-10-05'
AND LEG_DATE < '2013-12-29'
AND PAY_CODE = 'P_HOURLY'
AND PAID = 'True'
GROUP BY d2.DRIVER_ID
) as DriverHours
on DriverMiles.Driver_ID = DriverHours.Driver_ID

我也尝试过CTE,但它也不起作用。有没有人有任何建议?

1 个答案:

答案 0 :(得分:3)

您正在查询同一个表并通过同一列进行聚合。这意味着您可以使用条件聚合:

SELECT  d1.DRIVER_ID,
        SUM(CASE WHEN PAY_DESCRIPTION = 'Paid by Mileage'
                 THEN COALESCE(LOADED_MILES, 0) + COALESCE(EMPTY_MILES, 0)
                 ELSE 0
             END) AS Miles,
        SUM(CASE WHEN PAY_CODE = 'P_HOURLY' THEN HOURS ELSE 0 END) 
FROM DRIVERPAY d1
WHERE LEG_DATE >= '2013-10-05' AND
      LEG_DATE < '2013-12-29' AND
      ((PAY_DESCRIPTION = 'Paid by Mileage' AND PMT_STATE = 'X') OR
       (PAY_CODE = 'P_HOURLY' AND PAID = 'True' )
      )
GROUP BY d1.DRIVER_ID