0

When you add a new column from an existing column - do you had to use add column or can you just drop it in? My orig table dosn't have Previous Day or Next Day - those are the columns I'm adding. Should this work?

SELECT
ACCT_NUM,
PRODUCT,
Date_local,
CURRENTDAY,
LAG[CURRENTDAY,1,0] OVER(PARTITION BY ACCT_NUM ORDER BY Date_local DESC) AS PREVIOUSDAY,
LEAD[CURRENTDAY,1,0] OVER(PARTITION BY ACCT_NUM ORDER BY Date_local DESC) AS NEXTDAY,
FROM FINANCE.REVENUE03

Or I could alter table?

ALTER TABLE REVENUE03
ADD COLUMN PREVIOUSDAY=
    LAG[CURRENTDAY,1,0] OVER(PARTITION BY ACCT_NUM ORDER BY Date_local DESC);
ADD COLUMN NEXTDAY=
    LEAD[CURRENTDAY,1,0] OVER(PARTITION BY ACCT_NUM ORDER BY Date_local DESC)

END
5
  • This is not really a good thing to do, and Windows Functions can only appear in SELECT or ORDER BY clauses. I suggest you use a VIEW instead. Commented Nov 18, 2018 at 21:21
  • @Sami how about my edit using alter table - would that work? Commented Nov 18, 2018 at 21:28
  • im new! I don't know what that means to me I'm just creating a column - that is how you create a column. why would you need Order by? Commented Nov 18, 2018 at 21:33
  • Can't you just create a VIEW or even a FUNCTION instead of using a window function in a computed column which is not possible? Commented Nov 18, 2018 at 21:38
  • could you show me an example? other questions I have asked have directed me to add things in this exact way so I'm failing to see why this wouldn't work here Commented Nov 18, 2018 at 21:42

1 Answer 1

1

Simply, you can't use a window function there, instead create a VIEW or try to create a FUNCTION and use it with the computed column.

Why?

Cause Windowed functions can only appear in the SELECT or ORDER BY clauses.

So, I sugget to create a VIEW like

CREATE VIEW YourViewName
AS
SELECT ACCT_NUM,
       PRODUCT,
       Date_local,
       CURRENTDAY,
       LAG[CURRENTDAY,1,0] OVER(PARTITION BY ACCT_NUM ORDER BY Date_local DESC) AS PREVIOUSDAY,
       LEAD[CURRENTDAY,1,0] OVER(PARTITION BY ACCT_NUM ORDER BY Date_local DESC) AS NEXTDAY,
FROM FINANCE.REVENUE03
GO
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you. I've had other people on here say you can start with UPDATE TABLE OR ALTER TABLE - is that not the case? Do you have to create a new view like this with each change? You just select your table and can make updates - didn't think you had to create a new view
@newbie No, you cant use a window function there, and for the view, all what you need is to create it once and SELECT from it.
If there is already table 1, can't you select*table 1; alter table 1 ...etc. Why do i have to create a view if the table exists - i query it and then I alter it

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.