如何在 mysql 中的 where 子句中使用别名与超前滞后函数
How to use alias in where clause in mysql with lead lag functions
我正在尝试将值与别名进行比较,但它说无法识别列。文档说不能在 where 子句中使用别名
WITH CTE AS
(
SELECT
StockCode AS TopProduct,
COUNT(CustomerID) AS mostCustomers
FROM
dbfinalweek.`e-commerce`
GROUP BY
StockCode
ORDER BY
mostCustomers DESC
LIMIT 1
)
SELECT
StockCode AS stock, CustomerID,
LEAD(StockCode, 1) OVER (ORDER BY CustomerID, InvoiceDate) AS NextItem,
LAG(StockCode, 1) OVER () AS PreviousItem,
InvoiceDate
FROM
dbfinalweek.`e-commerce` AS table1
WHERE
(table1.StockCode = (SELECT CTE.TopProduct FROM CTE)) OR
(table1.NextItem = (SELECT CTE.TopProduct FROM CTE))
这是我的查询。知道如何让 Table1.NextItem
工作吗?
Windo功能不能直接使用,所以你必须为此制作第二个cte`
CREATE TABLE `e-commerce` (StockCode int,CustomerID int,mostCustomers int,InvoiceDate date)
with CTE AS
(
Select
StockCode as TopProduct
,count(CustomerID) as mostCustomers
from `e-commerce`
group by StockCode
order by mostCustomers desc
limit 1
),
cte2 as(
select
StockCode as stock
,CustomerID
, Lead(StockCode,1) over( order by CustomerID,InvoiceDate) as NextItem
,Lag(StockCode,1) over() as PreviousItem
,InvoiceDate
from `e-commerce` )
SELECT
* FROM cte2
WHERE (stock = (Select CTE.TopProduct from CTE)) OR (NextItem=(Select CTE.TopProduct from CTE))
stock | CustomerID | NextItem | PreviousItem | InvoiceDate
----: | ---------: | -------: | -----------: | :----------
db<>fiddle here
我正在尝试将值与别名进行比较,但它说无法识别列。文档说不能在 where 子句中使用别名
WITH CTE AS
(
SELECT
StockCode AS TopProduct,
COUNT(CustomerID) AS mostCustomers
FROM
dbfinalweek.`e-commerce`
GROUP BY
StockCode
ORDER BY
mostCustomers DESC
LIMIT 1
)
SELECT
StockCode AS stock, CustomerID,
LEAD(StockCode, 1) OVER (ORDER BY CustomerID, InvoiceDate) AS NextItem,
LAG(StockCode, 1) OVER () AS PreviousItem,
InvoiceDate
FROM
dbfinalweek.`e-commerce` AS table1
WHERE
(table1.StockCode = (SELECT CTE.TopProduct FROM CTE)) OR
(table1.NextItem = (SELECT CTE.TopProduct FROM CTE))
这是我的查询。知道如何让 Table1.NextItem
工作吗?
Windo功能不能直接使用,所以你必须为此制作第二个cte`
CREATE TABLE `e-commerce` (StockCode int,CustomerID int,mostCustomers int,InvoiceDate date)
with CTE AS ( Select StockCode as TopProduct ,count(CustomerID) as mostCustomers from `e-commerce` group by StockCode order by mostCustomers desc limit 1 ), cte2 as( select StockCode as stock ,CustomerID , Lead(StockCode,1) over( order by CustomerID,InvoiceDate) as NextItem ,Lag(StockCode,1) over() as PreviousItem ,InvoiceDate from `e-commerce` ) SELECT * FROM cte2 WHERE (stock = (Select CTE.TopProduct from CTE)) OR (NextItem=(Select CTE.TopProduct from CTE))
stock | CustomerID | NextItem | PreviousItem | InvoiceDate ----: | ---------: | -------: | -----------: | :----------
db<>fiddle here