如何拖拽描述(信息)

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

输入:

身份证 单位编号 租户姓名 净租金 保证金
1 #k1-30 Kkks私人有限公司 12.4 115000.12
2 14.4
3 16.4
4 #K1-40 皇冠私人有限公司 22.60 215000.12
5 24.60
6 26.60
7 #K14-01 Techno光伏有限公司 64.60 124230.12
8 27.60

输出:

身份证 单位编号 租户姓名 净租金 保证金
1 #k1-30 Kkks私人有限公司 12.4 115000.12
2 #k1-30 Kkks私人有限公司 14.4 115000.12
3 #k1-30 Kkks私人有限公司 16.4 115000.12
4 #K1-40 皇冠私人有限公司 22.60 215000.12
5 #K1-40 皇冠私人有限公司 24.60 215000.12
6 #K1-40 皇冠私人有限公司 26.60 215000.12
7 #K14-01 Techno光伏有限公司 64.60 124230.12
8 #K14-01 Techno光伏有限公司 27.60 124230.12

在 SQL Server 中,我必须向下拖动单元号、租户名称和保证金。但我只有唯一的列作为[单元号]。 在这种情况下,应该有相同的租户名称,但不同的单位号码是可能的。

sql sql-server
1个回答
0
投票

数据

CREATE TABLE mytable(
   Id                 INTEGER  NOT NULL 
  ,UnitNo          VARCHAR(80)
  ,TenantName      VARCHAR(50)
  ,NetRent         NUMERIC(6,2) NOT NULL
  ,SecurityDeposit NUMERIC(9,2)
);
INSERT INTO mytable
(Id,UnitNo,TenantName,NetRent,SecurityDeposit) VALUES 
(1,'#k1-30','Kkks Pte Ltd',12.4,115000.12),
(2,NULL,NULL,14.4,NULL),
(3,NULL,NULL,16.4,NULL),
(4,'#K1-40','crown Pte Ltd',22.60,215000.12),
(5,NULL,NULL,24.60,NULL),
(6,NULL,NULL,26.60,NULL),
(7,'#K14-01','Techno pv Ltd',64.60,124230.12),
(8,NULL,NULL,27.60,NULL);

使用以下查询

select
Id,
coalesce([UnitNo], max([UnitNo]) over (partition by [UnitNo1])) as [UnitNo1],
coalesce([TenantName], max([TenantName]) over (partition by [TenantName1])) as [TenantName1],
NetRent,  
coalesce([SecurityDeposit], max([SecurityDeposit]) over (partition by [SecurityDeposit1])) as [SecurityDeposit1]
  
from (
select t.*,
max(case when [UnitNo] is not null then Id end) over (order by Id) as [UnitNo1],
max(case when [TenantName] is not null then Id end) over (order by Id) as [TenantName1],
max(case when [SecurityDeposit] is not null then Id end) over (order by Id) as [SecurityDeposit1]
 
from mytable t
) t

或者为了更新,在查询中使用 CTE

;with t as
(
select
Id,UnitNo,TenantName,NetRent,SecurityDeposit,
coalesce([UnitNo], max([UnitNo]) over (partition by [UnitNo1])) as [UnitNo1],
coalesce([TenantName], max([TenantName]) over (partition by [TenantName1])) as [TenantName1],
coalesce([SecurityDeposit], max([SecurityDeposit]) over (partition by [SecurityDeposit1])) as [SecurityDeposit1]
  
from (
select t.*,
max(case when [UnitNo] is not null then Id end) over (order by Id) as [UnitNo1],
max(case when [TenantName] is not null then Id end) over (order by Id) as [TenantName1],
max(case when [SecurityDeposit] is not null then Id end) over (order by Id) as [SecurityDeposit1]
from mytable t
) t
  
)

update t
set UnitNo=[UnitNo1],
    TenantName=[TenantName1],
    SecurityDeposit=SecurityDeposit1


select * from mytable

dbfiddle

© www.soinside.com 2019 - 2024. All rights reserved.