SELECT
SUM(`PR Requests`),
CAR,
Request_State
FROM
(
SELECT DISTINCT
Po_Line_Amount AS `PR Requests`,
Project_Code AS CAR,
Request_State
FROM
Table1
WHERE NOT (
Request_State LIKE '%canceled%'
OR Request_State LIKE '%pulled_back%'
)
) t
该查询有效并返回正确总结的不同金额。我尝试在更大的查询中解决这些问题:
SELECT ID, Title, `Start Date`, `7ca. CAR` AS CAR, b.PR, c.Capex, c.PO_Committed AS `PO Committed`, c.PO_Invoiced AS `PO Invoiced`
FROM Table3 a
LEFT JOIN (
SELECT
SUM(`PR Requests`) AS PR,
CAR,
Request_State
FROM
(
SELECT DISTINCT
Po_Line_Amount AS `PR Requests`,
Project_Code AS CAR,
Request_State
FROM
Table1
WHERE NOT (
Request_State LIKE '%canceled%'
OR Request_State LIKE '%pulled_back%'
)
) t
) b ON b.CAR = a.`7ca. CAR`
LEFT JOIN (
SELECT Car_Number, SUM(Capex) AS Capex, SUM(PO_Committed) AS PO_Committed, SUM(PO_Invoiced) AS PO_Invoiced
FROM Table2
GROUP BY Car_Number
) c ON c.Car_Number = a.`7ca. CAR`
WHERE `Snapshot` = (SELECT MAX(`Snapshot`) FROM RandD_Playbook)
AND NOT ISNULL(PO_Committed)
GROUP BY
ID, Title
这样运行,但它给了我NULL的PR,我期望获得PR请求的SUM。我错了吗?
答案 0 :(得分:0)
如果PR
为NULL,并且由于您正在进行LEFT JOIN,这只能表示b.CAR = a.7ca. CAR
答案 1 :(得分:0)
弄清楚了;我突然想到在SELECT DISTINCT代码的t之后添加一个组。
SELECT ID, Title, `Start Date`, `7ca. CAR` AS CAR, b.PR, c.Capex, c.PO_Committed AS `PO Committed`, c.PO_Invoiced AS `PO Invoiced`
FROM Table3 a
LEFT JOIN (
SELECT
SUM(`PR Requests`) AS PR,
CAR,
Request_State
FROM
(
SELECT DISTINCT
Po_Line_Amount AS `PR Requests`,
Project_Code AS CAR,
Request_State
FROM
Table1
WHERE NOT (
Request_State LIKE '%canceled%'
OR Request_State LIKE '%pulled_back%'
)
) t
GROUP BY CAR
) b ON b.CAR = a.`7ca. CAR`
LEFT JOIN (
SELECT Car_Number, SUM(Capex) AS Capex, SUM(PO_Committed) AS PO_Committed, SUM(PO_Invoiced) AS PO_Invoiced
FROM Table2
GROUP BY Car_Number
) c ON c.Car_Number = a.`7ca. CAR`
WHERE `Snapshot` = (SELECT MAX(`Snapshot`) FROM RandD_Playbook)
AND NOT ISNULL(PO_Committed)
GROUP BY
ID, Title
清除了NULL。不知道为什么那里需要它,但它适用于所有情况,所以对我来说没问题。