Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

inner join - How to add the first value of a column in SQL over another grouping variable

I have a database with a table of the following kind:

customer_id customer_type customer_state state_date
1 A 0 2020-01-01
1 A 1 2020-01-05
1 B 2 2020-01-06
2 X 0 2019-02-07
2 Y 0 2019-02-07
2 X 0 2019-02-07
question from:https://stackoverflow.com/questions/65842505/how-to-add-the-first-value-of-a-column-in-sql-over-another-grouping-variable

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

1 Answer

0 votes
by (71.8m points)

One possibility, using ROW_NUMBER:

WITH cte AS (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY state_date) rn
    FROM yourTable
)

SELECT customer_id, customer_type, customer_state, state_date,
       MAX(CASE WHEN rn = 1 THEN customer_type END) OVER
           (PARTITION BY customer_id) first_type
FROM cte;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...