sql-server 根据Row_number条件获取结果

ih99xse1  于 2022-10-31  发布在  其他
关注(0)|答案(1)|浏览(135)

我有三张table:#T#T1#Maintable,我将为它们附加相应的DDL。

Create table  #T ( id int , reason varchar (50));    

insert into #T Values (1,'Texas for live music');
insert into #T Values (1,'Texas for BBQ');
insert into #T Values (2,'Wisconsin for dairy products');
insert into #T Values (2,'Wisconsin for Rock');
insert into #T Values (2,'Wisconsin for Bird');
insert into #T Values (3,'North Carolina for Pepsi');
insert into #T Values (4,'Missouri for Forest');
insert into #T Values (5,'Oklohoma for cowboy');
insert into #T Values (5,'Oklohoma for Native Americans');
insert into #T Values (5,'Oklohoma for oil and gas');

Create table  #T1 ( id int , reason varchar (50));   

insert into #T1 Values (1,'Texas for live music,BBQ');
insert into #T1 Values (2,'Wisconsin for dairy products, rock,bird');
insert into #T1 Values (3,'North Carolina for Pepsi');
insert into #T1 Values (4,'Missouri for Forest');
insert into #T1 Values (5,'Oklohoma for Native Americans,oil and gas');

Create table #MainTable (id int, State varchar(20),Capital varchar(30),Governer varchar(30)); 

Insert into #Maintable values (1,'Texas','Austin','A');
Insert into #Maintable values (2,'Wisconsin','Madison','B');
Insert into #Maintable values (3,'North Carolina','Releigh','C');
Insert into #Maintable values (4,'Missouri','Jefferson City','D');
Insert into #Maintable values (5,'Oklohoma','Oklohoma city','E');

预期输出

| 识别码|原因|州/省|资本|调速器|
| - -|- -|- -|- -|- -|
| 一个|德州现场音乐、烧烤|德克萨斯州|奥斯汀|A级|
| 2个|威斯康星州州的乳制品,岩石,鸟|威斯康星州|麦迪逊|B|
| 三个|北卡罗来纳州的百事可乐|北卡罗来纳州|重新校准|C类|
| 四个|密苏里州森林|密苏里州|杰佛逊城|D级|
| 五个|Oklohoma为美洲原住民、石油和天然气|奥克洛霍马|奥克洛霍马市|E级|
我有几个表,我将根据标准从表#T中筛选记录,并与其他表连接以获得更多列,但在cte的帮助下,我无法进行筛选。如果第一个表#T有多个ID,则我们将使用另一个表#T1中的原因。如果它只有一个ID,则我们将使用表#T中的原因,最后,我们将与#main表连接以获取其他记录。我添加了一个描述更多内容的图像。非常感谢您的帮助。我们可以测试所有这些临时表
场景是:

  • 如果原因在#T表中出现多次,则使用#T1表
  • 如果reason在#T表中仅出现一次,则仅使用#T,这是第一个表

下面是我的编码尝试:

with cte as (
    select *, ROW_NUMBER() over (partition by id order by id) rn 
    from #T 
)
select mt.id, state, capital, Governer,
       case when c.rn > 1 
            then #t1.reason 
            else c.reason 
       end as reason
from cte c 
join #t1           on c.id = #t1.id 
join #maintable mt on c.id = mt.id

我得到了更多的结果,我期待只有5个记录。我猜有一些问题,在我的行_号码。帮助是感激。

ifmq2ha2

ifmq2ha21#

您应该首先从表“#T”中为每个ID提取排名值。然后,您可以结合使用COALESCE函数和LEFT JOIN运算来解决您的问题:

WITH #T_ranked AS (
    SELECT *, ROW_NUMBER() OVER(PARTITION BY id ORDER BY reason) AS rn 
    FROM #T
)
SELECT m.id, 
       COALESCE(#T1.reason, #T_ranked.reason) AS Reason,
       m.State, 
       m.Capital, 
       m.Governer
FROM      #Maintable m
LEFT JOIN #T1 ON m.id = #T1.id
LEFT JOIN #T_ranked ON m.id = #T_ranked.id AND #T_ranked.rn = 1

LEFT JOIN操作将保留“MainTable”中的id,而COALESCE函数将使第一个非空参数成为“Reason”新字段的值,在特定情况下,它将检查“#T1.Reason”是否为空,如果是,则它将分配“#T2.Reason"。在“#T1.Reason”中具有现有对应者的来自“*#T.Reason *”的值将永远不会以这种方式被选择。
检查演示here

相关问题