你可以预先分析 "C "值,然后用它来删除它们?
DECLARE @Data TABLE (
[Var] VARCHAR(1),
Value INT,
ID INT);
INSERT INTO @Data SELECT 'A', 1, 1;
INSERT INTO @Data SELECT 'B', 2, 1;
INSERT INTO @Data SELECT 'C', 3, 1;
INSERT INTO @Data SELECT 'A', 2, 2;
INSERT INTO @Data SELECT 'B', 4, 2;
INSERT INTO @Data SELECT 'C', 6, 2;
WITH CValues AS (
SELECT
Value
@Data
WHERE
[Var] = 'C')
SELECT
d.[Var],
CASE WHEN d.[Var] != 'C' THEN d.Value - c.Value ELSE d.Value END AS Value,
@Data d
LEFT JOIN CValues c ON c.ID = d.ID;
...但是,是的,自我连接可能是一个更好的解决方案。
DECLARE @Data TABLE (
[Var] VARCHAR(1),
Value INT,
ID INT);
INSERT INTO @Data SELECT 'A', 1, 1;
INSERT INTO @Data SELECT 'B', 2, 1;
INSERT INTO @Data SELECT 'C', 3, 1;
INSERT INTO @Data SELECT 'A', 2, 2;
INSERT INTO @Data SELECT 'B', 4, 2;
INSERT INTO @Data SELECT 'C', 6, 2;
SELECT
d.[Var],
CASE WHEN d.[Var] != 'C' THEN d.Value - c.Value ELSE d.Value END AS Value,