您可以将 3 个 CTE 合二为一吗?
Can you combine 3 CTE's into one?
我有一个用 3 个 CTE 编写的查询,我需要仅使用 1 个 CTE 来获得完全相同的结果。有人可以帮助我吗?
WITH Q1(cid, sumEP) AS
(
SELECT customerid, SUM(Extendedprice)
From "Invoices"
GROUP BY customerid
), Q2(cid, oid, mf) AS
(
SELECT DISTINCT customerid, orderid, freight
FROM "Invoices"
), Q3 AS
(
SELECT cid, SUM(mf) AS smf
FROM Q2
GROUP BY cid
)
SELECT Q1.cid, sumEP + smf AS total
FROM Q1
JOIN Q3 ON Q1.cid = Q3.cid
LIMIT 10
smf
是每个订单(对于同一客户)的 freight
不同值的总和,但是您可以使用 sum(distinct freight)
所以我会建议这个查询:
WITH Q(customerid, orderid, total) AS
(
SELECT customerid, orderid, SUM(Extendedprice) + SUM(DISTINCT freight)
FROM Invoices
GROUP BY customerid, orderid
)
SELECT customerid, SUM(total) AS total
FROM Q
GROUP BY customerid
ORDER BY 2 DESC
LIMIT 10;
当不存在同一客户的不同订单运费相同的情况时,则可以简化为:
SELECT customerid, SUM(Extendedprice) + SUM(DISTINCT freight) AS total
FROM Invoices
GROUP BY customerid
ORDER BY 2 DESC
LIMIT 10
请注意,我添加了一个 order by
,这样您就可以用它背后的一些逻辑来限制结果——在本例中,总计排名前 10。根据需要更改。
我有一个用 3 个 CTE 编写的查询,我需要仅使用 1 个 CTE 来获得完全相同的结果。有人可以帮助我吗?
WITH Q1(cid, sumEP) AS
(
SELECT customerid, SUM(Extendedprice)
From "Invoices"
GROUP BY customerid
), Q2(cid, oid, mf) AS
(
SELECT DISTINCT customerid, orderid, freight
FROM "Invoices"
), Q3 AS
(
SELECT cid, SUM(mf) AS smf
FROM Q2
GROUP BY cid
)
SELECT Q1.cid, sumEP + smf AS total
FROM Q1
JOIN Q3 ON Q1.cid = Q3.cid
LIMIT 10
smf
是每个订单(对于同一客户)的 freight
不同值的总和,但是您可以使用 sum(distinct freight)
所以我会建议这个查询:
WITH Q(customerid, orderid, total) AS
(
SELECT customerid, orderid, SUM(Extendedprice) + SUM(DISTINCT freight)
FROM Invoices
GROUP BY customerid, orderid
)
SELECT customerid, SUM(total) AS total
FROM Q
GROUP BY customerid
ORDER BY 2 DESC
LIMIT 10;
当不存在同一客户的不同订单运费相同的情况时,则可以简化为:
SELECT customerid, SUM(Extendedprice) + SUM(DISTINCT freight) AS total
FROM Invoices
GROUP BY customerid
ORDER BY 2 DESC
LIMIT 10
请注意,我添加了一个 order by
,这样您就可以用它背后的一些逻辑来限制结果——在本例中,总计排名前 10。根据需要更改。