如何填补表格的空白。我有一个示例数据
DECLARE @Table TABLE
( Rule_ID VARCHAR(10),
Name VARCHAR(10),
Age INT
)
INSERT INTO @Table(Rule_ID,Name,Age)
VALUES
('Rule_01','Mohan',29),
('Rule_01','Manasa',25),
('Rule_03','Raju',29),
('Rule_03','Miju',25),
('Rule_05','Ramu',30),
('Rule_05','Rao',35)
Select * from @Table
当前结果集
Rule_ID名称年龄
Rule_01 Mohan 29
Rule_01 Manasa 25
Rule_03 Raju 29
Rule_03 Miju 25
Rule_05 Ramu 30
Rule_05 Rao 35
我想要这样的输出
Rule_ID名称年龄
Rule_01 Mohan 29
Rule_01 Manasa 25
Rule_02 NULL NULL
Rule_03 Raju 29
Rule_03 Miju 25
Rule_04 NULL NULL
Rule_05 Ramu 30
Rule_05 Rao 35
我已经从Stack溢出中尝试了很多答案。但我无法前进。建议我
答案 0 :(得分:1)
Rule_ID
上的部队。使用Rule_ID
的最后两位数。
DECLARE @Table TABLE
( Rule_ID VARCHAR(10),
Name VARCHAR(10),
Age INT
)
INSERT INTO @Table(Rule_ID,Name,Age)
VALUES
('Rule_01','Mohan',29),
('Rule_01','Manasa',25),
('Rule_03','Raju',29),
('Rule_03','Miju',25),
('Rule_05','Ramu',30),
('Rule_05','Rao',35)
DECLARE @MaxValue INT
SELECT @MaxValue = MAX(CAST(RIGHT(Rule_ID, 2) AS INT)) from @Table
DECLARE @Id INT = 1
;WITH Tmp (Id)
AS
(
SELECT @Id AS Id
UNION ALL
SELECT Id +1 FROM Tmp
WHERE
Id < @MaxValue
)
SELECT * FROM @Table
UNION ALL
SELECT 'Rule_' + RIGHT('00' + CAST(A.Id AS NVARCHAR(2)), 2), NULL, null FROM Tmp A
WHERE
NOT EXISTS
(
SELECT TOP 1 1 FROM @Table T
WHERE
T.Rule_ID = 'Rule_' + RIGHT('00' + CAST(A.Id AS NVARCHAR(2)), 2)
)
ORDER BY Rule_ID
生产
Rule_ID Name Age
---------- ---------- -----------
Rule_01 Mohan 29
Rule_01 Manasa 25
Rule_02 NULL NULL
Rule_03 Raju 29
Rule_03 Miju 25
Rule_04 NULL NULL
Rule_05 Ramu 30
Rule_05 Rao 35
答案 1 :(得分:1)
获得所需结果的一种方法是,如果事先知道不同的Rule_ID(即修复)并且您没有应该存在的不同Rule_ID的来源,则使用table value constructor,如下所示:
SELECT Rules.Rule_ID, t.Name, t.Age
FROM (
VALUES ('Rule_01'),('Rule_02'),('Rule_03'),('Rule_04'),('Rule_05')
) AS Rules (Rule_ID)
LEFT JOIN @Table t ON t.Rule_ID = Rules.Rule_ID
这适用于固定数据,但如果Rule_ID的范围取决于表中的数据,并且您希望填补最低和最高数字之间的差距,则另一种解决方案可能会更好。
答案 2 :(得分:1)
SELECT tally.Rule_ID ,Name , Age
FROM (
SELECT TOP(99) Rule_ID='Rule_' + left('0'+cast(row_number() over (order by (select null)) as varchar(2)), 2)
FROM sys.all_objects ) AS tally
LEFT JOIN @Table t ON t.Rule_ID = tally.Rule_ID