比较date1和date2的SQL case语句,输出date2

比较date1和date2的SQL case语句,输出date2,sql,Sql,我对SQL比较陌生,对Excel比较熟悉。我试图比较两个不同列(和表)中的两个日期,但还没有弄清楚如何做。我读过帖子/做过谷歌搜索,但没有找到答案 示例: select table1.userID, table1.date1, case when table1.date1 = table2.date2 then table2.date2 end from table1 left join table2 on table1.userID = table2.userID s

我对SQL比较陌生,对Excel比较熟悉。我试图比较两个不同列(和表)中的两个日期,但还没有弄清楚如何做。我读过帖子/做过谷歌搜索,但没有找到答案

示例:

select table1.userID,
table1.date1,
case 
     when table1.date1 = table2.date2 
     then table2.date2 end
from table1
left join table2
on table1.userID = table2.userID

select table1.userID,
table1.date1,
case 
     when table1.date1 > table2.date2 
     then table2.date 2 end
from table1
left join table2
on table1.userID = table2.userID
我在示例1中查看的输出将告诉我,对于在特定日期有约会的每个用户,他们是否也在当天完成了测试。表1包含所有用户ID及其所有约会日期,表2包含用户ID和测试日期

例如,我想看看在诊断日期之后是否有测试发生(表1有诊断日期,表2有测试日期)


我能够使用两个查询完成第一个示例,每个表一个查询,然后使用excel指示表1中的ID/日期组合是否也在表2中。请帮我弄清楚如何用SQL写这个!:)

你就快到了。尝试:

select 
table1.userID,
table1.date1,
table2.date2
from 
table1
left join table2 on table1.userID = table2.userID
where table1.date1 = table2.date2
-- this select statement will show all records where the date is the same.
-- you may have to amend the WHERE clause depending on your date field datatype



select 
table1.userID,
table1.date1,
table2.date2
from table1
left join table2 on table1.userID = table2.userID
where table1.date2 > table2.date1 
-- this select statement will show all records where the date exists and is larger.
-- you may have to amend the WHERE clause depending on your date field datatype

如果没有示例数据,我将日期1和日期2混淆,因此您必须检查以确保它采用了正确的日期字段

你使用什么数据库?这是一个ODBC数据库,我正在通过DBeaver访问它(这是一个电子健康记录,我有只读访问权限,所以我无法创建表/视图)。我建议在你的问题中添加数据-查询前的数据(原始)和你期望通过查询获得的数据。示例数据和期望的结果将非常有用。“比较”是相当广泛的。您在案例陈述中缺少了“其他”条件。但是,我认为您还需要在左侧联接中添加日期比较,以避免重复结果。唯一需要注意的是可能出现重复行。正确,但如果不了解完整过程或数据的获取和存储方式,则很难理解。提交者很接近,只是需要WHERE语句。实际上我误解了你的答案。
where
条件需要上移到join子句中。否。在左联接之后对内部表进行筛选将使其减少为内部联接。可能会有没有测试的预约,这取决于数据库结构是如何定义的。阅读原始问题:“表1包含所有用户ID及其约会日期,表2包含用户ID和测试日期”。是的,如果USERID有多个约会,您将得到重复的行,但是如果USERID对于每个约会都是唯一的,那么它将按预期工作。在我们看到实际数据之前很难知道。