[英]SQL - All values from first table joined with first value from second one and null otherwise
is it possible to do a join like this in SQL: 是否可以在SQL中像这样进行联接:
We want to join the two tables on SessionID, but the resulting table should return full table "Pageviews" combined with only a single value of Sessions for each unique SessionID (for others the value should be NULL, please see the 'Desired Result' table for explanation). 我们要在SessionID上连接两个表,但是结果表应该返回完整的表“ Pageviews”,并且每个唯一SessionID的Session值只有一个 (其他值应该为NULL,请参见“所需结果”表)进行解释)。
Thank you. 谢谢。
Based on you requirement( and truly based on the data provided) the below code would do the work - 根据您的要求(并真正基于提供的数据),以下代码可以完成工作-
declare @pageviews table(sessionid char(10), pageviews tinyint)
declare @sessions table(sessionid char(10), sessions tinyint)
insert into @pageviews values
('FA-1',34),
('FA-1',36),
('FA-2',23),
('FA-3',11),
('FA-3',32),
('FA-3',25)
insert into @sessions values
('FA-1',23),
('FA-2',14),
('FA-3',9)
;with cte as
(select sessionid,pageviews,ROW_NUMBER() OVER(PARTITION BY sessionid ORDER BY sessionid desc) rn
from @pageviews)
select p.sessionid,p.pageviews,case when rn = 1 then s.sessions else null end as sessions
from cte p inner join @sessions s
on p.sessionid = s.sessionid
You can do like this. 你可以这样
SELECT T2.SessionID,T2.pageviews,T1.Sessions
FROM sessions AS T1
RIGHT JOIN
(
SELECT ROW_NUMBER() OVER(PARTITION BY sessionid ORDER BY sessionid DESC) AS ROWNUM,
sessionid,
pageviews
FROM pageviews
) AS T2
ON T1.sessionid = T2.sessionid AND T2.ROWNUM = 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.