英文:
Join two tables statement
问题
我有两个表格,如下所示:
Table1:
| Entity | Value |
|---------------------|-----|
| A| 5|
| B| 10|
Table2:
| Date|
|---------|
| 1/1/2023|
| 2/1/2023|
| 3/1/2023|
| 4/1/2023|
| 5/1/2023|
期望的最终结果:
| Entity | Value |Date|
|---------------------|-----|----|
| A| 5|1/1/2023|
| A| 6|2/1/2023|
| A| 7|3/1/2023|
| A| 8|4/1/2023|
| A| 9|5/1/2023|
| B| 10|1/1/2023|
| B| 11|2/1/2023|
| B| 12|3/1/2023|
| B| 13|4/1/2023|
| B| 14|5/1/2023|
通常的左连接可以将table2中的**date**列连接到table1,但如何根据日期列的'行号'递增**value**列?
英文:
I have two tables as shown below:
Table1:
Entity | Value |
---|---|
A | 5 |
B | 10 |
Table2:
Date |
---|
1/1/2023 |
2/1/2023 |
3/1/2023 |
4/1/2023 |
5/1/2023 |
The final result expected:
Entity | Value | Date |
---|---|---|
A | 5 | 1/1/2023 |
A | 6 | 2/1/2023 |
A | 7 | 3/1/2023 |
A | 8 | 4/1/2023 |
A | 9 | 5/1/2023 |
B | 10 | 1/1/2023 |
B | 11 | 2/1/2023 |
B | 12 | 3/1/2023 |
B | 13 | 4/1/2023 |
B | 14 | 5/1/2023 |
A usual left join can join the date column from table2 to table1 but how do I increment the value column based on 'row numbers' from the date column?
答案1
得分: 2
cross join 会给你两个表的笛卡尔积(即将t1
中的每一行与t2
中的每一行匹配),row_number 将提供你的新值:
select t1.Entity, t2.Date,
t1.Value - 1 + Row_Number() over(partition by entity order by date) as Value
from t1
cross join t2
order by Value;
英文:
A cross join will give you the cartesian product of your two tables (ie match each row in t1
to every row in t2
), row_number will provide your new values:
select t1.Entity, t2.Date,
t1.Value - 1 + Row_Number() over(partition by entity order by date) as Value
from t1
cross join t2
order by Value;
答案2
得分: 2
你可以首先使用 cross join 运算符来获取应用于所有实体的日期,然后使用 SQL 窗口函数 为每一行设置当前值。
以下是示例代码:
SELECT
entity,
dt,
value+COUNT(1) OVER (PARTITION BY entity order by dt)-1 as value
FROM
table_1
CROSS JOIN
table_2
ORDER BY entity,dt
RUNNING EXAMPLE SQLFIDDLE LINK
示例输出:
entity | dt | value |
---|---|---|
A | 2023-01-01 | 5 |
A | 2023-02-01 | 6 |
A | 2023-03-01 | 7 |
A | 2023-04-01 | 8 |
A | 2023-05-01 | 9 |
B | 2023-01-01 | 10 |
B | 2023-02-01 | 11 |
B | 2023-03-01 | 12 |
B | 2023-04-01 | 13 |
B | 2023-05-01 | 14 |
英文:
You can first use cross join operator to get dates applied all entity, and then use SQL window function to set the current value for each row.
See the following code as example:
SELECT
entity,
dt,
value+COUNT(1) OVER (PARTITION BY entity order by dt)-1 as value
FROM
table_1
CROSS JOIN
table_2
ORDER BY entity,dt
RUNNING EXAMPLE SQLFIDDLE LINK
example output:
entity | dt | value |
---|---|---|
A | 2023-01-01 | 5 |
A | 2023-02-01 | 6 |
A | 2023-03-01 | 7 |
A | 2023-04-01 | 8 |
A | 2023-05-01 | 9 |
B | 2023-01-01 | 10 |
B | 2023-02-01 | 11 |
B | 2023-03-01 | 12 |
B | 2023-04-01 | 13 |
B | 2023-05-01 | 14 |
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论