LEFT JOIN未返回期望的结果

问题描述 投票:0回答:1

我有两个查询,每个查询的输出如下所示:

SELECT UserID, ActivityDate, ActivityDay, ActivityTime
FROM Activities 
WHERE ActivityType='MYS'

enter image description here

SELECT USerID, TimeFrom, TimeTo, ActivityDay
FROM [dbo].[userActivities]  WHERE UserID=123

enter image description here

预期结果:

两个查询都可以使用以下链接:

  • Activities.UserID = userActivities.UserID
  • Activities.ActivityDay = userActivities.ActivityDay

我需要从第一个数据集中获得所有4行,并且需要添加的新列基于第二个查询中的值。对于ActvityDay 7,有两条记录,因为在下一个对ActvityDay 7的查询中,有两条记录。

enter image description here

我试图使用LEFT JOIN提取数据,但未获得所需的结果。有人可以让我知道我在做什么错吗?

我正在尝试查询:

SELECT DISTINCT AD.UserID, AD.ActiityDate, AD.ActivityDay, AD.ActivityTime,
CASE WHEN AD.ActiityDate = userActivities.ActivityDay THEN 'Yes' ELSE 'No' END AS [ActivityExists],
CASE WHEN AD.ActiityDate = userActivities.ActivityDay THEN UA.TimeFrom ELSE '' END AS [Time],
FROM Activities AD LEFT JOIN userActivities UA ON AD.UserID=UA.UserID 
AND AD.ActiityDate = userActivities.ActivityDay

我有两个查询,每个查询的输出如下所示:SELECT UserID,ActivityDate,ActivityDay,ActivityTime from Activities WHERE ActivityType ='MYS'SELECT USerID,TimeFrom,...

sql-server join left-join ssms
1个回答
0
投票
您将联接和CASE表达式基于错误的列。另外,由于您为表使用别名,因此请使用别名,并且不要混合使用表名和别名。试试这个:
© www.soinside.com 2019 - 2024. All rights reserved.