SQL内部连接与过滤
我有2个表,如下所示:
Table1:
ID Date
1 2022-01-01
2 2022-02-01
3 2022-02-05
Table2
ID Date Amount
1 2021-08-01 15
1 2022-02-10 15
2 2022-02-15 20
2 2021-01-01 15
2 2022-02-20 20
1 2022-03-01 15
我想在table2
中选择行,以便在table1
中仅超过date
的行。 > table2 并计算每个子集的金额和max(date)
in table2
在每个子集 in ID中分组。 因此,结果看起来像
ID Date Amount
1 2022-03-01 30
2 2022-02-20 40
SQL Newbie ...我尝试了一个内部连接,但无法将日期过滤器传递...
尝试查询:
with table1 as (select * from table1)
,table2 as (select * from table2)
select * from table1 a
inner join table2 b on (a.id=b.id)
谢谢!
I have 2 tables as follows:
Table1:
ID Date
1 2022-01-01
2 2022-02-01
3 2022-02-05
Table2
ID Date Amount
1 2021-08-01 15
1 2022-02-10 15
2 2022-02-15 20
2 2021-01-01 15
2 2022-02-20 20
1 2022-03-01 15
I want to select the rows in Table2
such that only rows past the Date
in Table1
are selected in Table2
and calculate a sum of amounts of each subset and max(date)
in Table2
for each subset grouped
by ID.
So the result would look like
ID Date Amount
1 2022-03-01 30
2 2022-02-20 40
SQL newbie here...I tried an inner join, but wasnt able to pass the date filter along...
Tried query:
with table1 as (select * from table1)
,table2 as (select * from table2)
select * from table1 a
inner join table2 b on (a.id=b.id)
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
就像保罗一样,我会使用一个加入,但我会在ON上放置条款,因此,如果您加入更多桌子,则SQL Optimizer的清洁程序更加清洁,以查看每个表/联接基础上的意图。我还将在桌子上使用别名并使用别名,因此该价值的来源没有混乱的余地,这再次使习惯使生活更轻松,而在编写更复杂的SQL或将其切成更大的代码块中。
因此,有了一些CTE的数据:
以下SQL:
Much like Paul, I would use a JOIN but I would put the clauses on the ON, so if you join to more tables, it's cleaner for the SQL optimizer to see what is the intent on a per table/join basis. I would also use aliases on tables and use the alias, so there is no room for confusion where the value is coming from, which again as a habit makes life easier when composing more complex SQL or cut'n'pasting into bigger blocks of code.
so with some CTE's for the data:
The following SQL:
这是我将如何使用雪花完成的方式:
获取数据
现在使用SELECT RESTILE
Here is how I would do this with Snowflake:
Now obtain the data using a select
Results
不熟悉雪花,但是应该有效的标准SQL查询是:
请注意,由于您仅需要Table2中的数据,因此存在 在内部连接中都可取,并且在几乎所有情况下都会更多表现胜于联赛,最糟糕的是。
Not personally familiar with Snowflake but a standard SQL query that should work would be:
Note that because you are only requiring data from Table2, an exists is preferable over an inner join and in almost all cases will be more performant than a join, at worst the same.