Обратите внимание на мои комментарии.
-- 1. SAMPLE DATA
DECLARE @Data TABLE
(
ID INT IDENTITY(1,1),
EntityId INT,
[Param] VARCHAR(25),
[Value] VARCHAR(25)
);
DECLARE @Param TABLE
(
[Param] VARCHAR(25)
);
INSERT INTO @Param([Param])
VALUES ('Param 1'),('Param 2'),('Param 3')
INSERT INTO @Data (EntityId, [Param], [Value])
VALUES(1, 'Param 1', 'Value 1'),(1, 'Param 2', 'Value 2'),(1, 'Param 3', 'Value 3'),
(2, 'Param 1', 'Value 1'),(2, 'Param 3', 'Value 3'),(3, 'Param 1', 'Value 1'),
(3, 'Param 3', 'Value 3'),(4, 'Param 1', 'Value 1');
-- 2. How to get ALL values
SELECT
dist.EntityId,
p.[Param],
[Value] = REPLACE(p.[Param], 'Param','Value')
FROM
(
SELECT DISTINCT d.EntityId
FROM @data AS d -- OR WHEREEVER I CAN GET A DISTINCT LIST OF EntityIDs
) AS dist(EntityId)
CROSS JOIN @param AS p;
-- 3. How to identify MISSING values
SELECT
dist.EntityId,
[Param] = CAST(p.[Param] AS varchar(25)),
[Value] = CAST(REPLACE(p.[Param], 'Param','Value') AS varchar(25))
FROM
(
SELECT DISTINCT d.EntityId
FROM @data AS d -- OR WHEREEVER I CAN GET A DISTINCT LIST OF EntityIDs
) AS dist(EntityId)
CROSS JOIN @param AS p
EXCEPT
SELECT d.EntityId, d.[param], d.[value]
FROM @data AS d;
-- 4. How to add missing values
INSERT @data
SELECT
dist.EntityId,
[Param] = CAST(p.[Param] AS varchar(25)),
[Value] = CAST(REPLACE(p.[Param], 'Param','Value') AS varchar(25))
FROM
(
SELECT DISTINCT d.EntityId
FROM @data AS d -- OR WHEREEVER I CAN GET A DISTINCT LIST OF EntityIDs
) AS dist(EntityId)
CROSS JOIN @param AS p
EXCEPT
SELECT d.EntityId, d.[param], d.[value]
FROM @data AS d;