比较一个表中的行 - 取决于其他列

时间:2016-06-06 12:54:46

标签: sql sql-server tsql

我的表格中有两列,Project列和configuration列。 configuration列连接由" _"分隔的3列。 我需要为每个项目选择仅在此项目中不同的列。

我不知道有多少项目,而且每个项目的唯一列都不同。 例如,这个表我有:

enter image description here

如您所见,项目1中的不同列是第1列和第3列。 在项目2中是第3列,在项目4中是第2列。 我想在每个行的查询中只查看此项目中不同的列

1 个答案:

答案 0 :(得分:0)

如果您别无选择,只能处理您发布的数据(就像它刚刚递交给您而您没有追索权,只能用于制作)

你可以试试这个:

-- Declare the variable for usage later
DECLARE @Project INT
SET @Project = 1

-- Let's use a temp table, say #t2
IF OBJECT_ID('tempdb..#t2') is  null
BEGIN
    -- Just trying: Split the Configuration string since
    --   it would appear the positions are in place
    --   at least in your example
    SELECT * INTO #t2 FROM (
    SELECT COUNT(*) as cnt, Substring(Configuration, 1, 2) AS Col1
        , Substring(Configuration, 4, 2) AS Col2
        , Substring(Configuration, 7, 2) AS Col3
    FROM yourTable --Replace with your table name
    WHERE Project = @Project -- Variable in use here
    GROUP BY Substring(Configuration, 1, 2) 
        , Substring(Configuration, 4, 2) 
        , Substring(Configuration, 7, 2) 
    ) t1
END

-- End select to show the project and the columns that are different
SELECT DISTINCT @Project AS Project, LEFT(REPLACE(Col1, 'A', 1),1) AS DiffColumnNum FROM #t2 GROUP BY Col1 
    HAVING  (COUNT(*) <> (SELECT COUNT(*) FROM #t2)) -- Weird having clause :)
UNION
SELECT DISTINCT @Project AS Project, LEFT(REPLACE(Col2, 'B', 2),1) AS DiffColumnNum FROM #t2 GROUP BY Col2 
    HAVING  (COUNT(*) <> (SELECT COUNT(*) FROM #t2))
UNION
SELECT DISTINCT @Project AS Project, LEFT(REPLACE(Col3, 'C', 3),1) AS DiffColumnNum FROM #t2 GROUP BY Col3 
    HAVING  (COUNT(*) <> (SELECT COUNT(*) FROM #t2))

我同意你问题区的评论;最好规范化,但如果你对此事没有发言权,请尝试使用此代码。我知道,它没有经过优化,但它可能会成功。