在SQL中使用日期连接表格

huangapple go评论112阅读模式
英文:

Joining tables with dates IN SQL

问题

如何在SQL中连接这两个表以获得所需的视图?
我有很多产品。
我尝试将产品连接起来,然后在开始日期和结束日期之间选择日期,但没有成功。
我该如何做?

英文:

spread-sheet rendering of two tables given and view wanted

How I can JOIN these tables in SQL to have that view?
I have a lot of products.

I TRIED TO JOIN PRODUCT THEN DATE BETWEEN START_DATE AND END_DATE and it's not working.
How I can do this?

答案1

得分: 1

使用子查询是解决这种情况的更好方式,因为您需要一个范围输出。

SELECT
    *
FROM
    table1
WHERE
    table1.data BETWEEN (SELECT data_start FROM table2) AND (SELECT data_end FROM table2)

其输出与您的预期输出相匹配。

这里是Fiddle

并确保table2中只有1条记录,以便查询可以精确选择一个起始日期和结束日期,否则在BETWEEN子查询中使用MAX与值。

英文:

Using subquery is a better way to address this scenario since you need a ranged output.

SELECT
	*
FROM
	table1
WHERE
	table1.data BETWEEN (SELECT data_start FROM table2) AND (SELECT data_end FROM table2)

Its output matches your expected output.

Here's the Fiddle

And make sure there's only 1 record in table2 so that query can pick exactly one start and end date, otherwise, use MAX with the values in the BETWEEN subqueries.

huangapple
  • 本文由 发表于 2023年7月4日 21:21:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/76613096.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定