简体   繁体   English

SQL-第一个表中的所有值与第二个表中的第一个值连接在一起,否则为null

[英]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

SQLFiddle SQLFiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 第一个表的所有行与第二个表连接 - all rows from the first table joined with the second table 如果第一个表中的值为 null,如何从第二个表中获取值 - How to get value from the second table if it's null in the first one SQL连接,从第二个表中提取值并将其添加到第一个表中 - Sql join, extract value from the second table and add it to the first one 从第一个表中选择所有值,从第二个表中选择第一个值 - Select all values from first table and ONLY first value from second table 连接两个表,使用第一个的值,除非它是 null,否则使用第二个的值 - Join two tables, using value from the first unless it is null, otherwise use value from the second SQL-基于一个表与另一个表的联接(第一个表的行值到第二个表的列值) - SQL - Joining one table with another based on ( Row value from first table to Column value of second table) 从连接到第一张桌子的第二张桌子中获取最新记录 - Get latest record from second table left joined to first table 如何通过使用第二个SQL的名称从第一个表中删除值 - How to delete values from first table by using name of the second sql 从 SQL 中的逗号分隔值获取第一个或第二个值 - Get first or second values from a comma separated value in SQL 将联接表中的值合并为一个值 - Consolidate values from joined table into one value
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM