SQL选择列等价

时间:2012-01-25 16:12:47

标签: sql sql-server

我有一个表可以保存其他表(实体)的可能状态。 但现在我需要找到两个实体之间的状态等价。 表结构就是这样的

ID   TableID   StateValue   StateDefinition  StateDescription
================================================================
1    1         1            Created          Just created
2    1         2            Dropped          Just Dropped
3    2         1            Created          Just Created
4    2         2            Aproved          Passed the revision
5    2         3            Dropped          Just dropped

我希望得到相同的(比较状态文本),结果得到这个:

   TableID1     StateValue1       TableID2       StateValue2    StateDefinition
   =============================================================================
   1            1                 2              1              Created
   1            2                 2              3              Dropped

我的问题是,怎么办呢?

2 个答案:

答案 0 :(得分:3)

自我加入桌面。

一般情况可能如下:

SELECT A.TableID as TableId1, 
       A.StateValue as StateValue1, 
       B.TableId as TableId2, 
       B.StateValue as StateValue2,
       A.StateDefinition
FROM
  Table A 
INNER JOIN Table B 
  ON (A.TableId <> B.TableId and A.StateDefiniton = B.StateDefinition)

答案 1 :(得分:2)

select t1.TableID as TableID1,
    t1.StateValue as StateValue1,
    t2.TableID as TableID2,
    t2.StateValue as StateValue2,
    t1.StateDefinition  
from MyTable t1
inner join MyTable t2 on t1.TableID = 1 and t2.TableID = 2
where t1.StateValue = t2.StateValue 
    and t1.StateDefinition  = t2.StateDefinition