Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
343 views
in Technique[技术] by (71.8m points)

How to use alias in where clause in mysql with lead lag functions

I am trying to compare value with an alias but it says scolumn not recognized. Docs says can't use alias in where clause

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))

Here is my query. Any idea how I could make Table1.NextItem work?

question from:https://stackoverflow.com/questions/65864724/how-to-use-alias-in-where-clause-in-mysql-with-lead-lag-functions

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Windo function can't be used directly so you must make a second cte for that`

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...