简体   繁体   English

T-SQL:表中的逻辑唯一表行

[英]T-SQL: logical unique table rows in table

I have simple table containing information about bidirectional links between elements. 我有一个简单的表,包含有关元素之间的双向链接的信息。 Table looks like this: 表看起来像这样:

link_id | link_side_a_element_id | link_side_b_element_id
---------------------------------------------------------
      1 |                    100 |                    200
      2 |                    200 |                    100
      3 |                    300 |                    400
      4 |                    400 |                    300

All I want is to select unique links between elements, no matter which element is sideA or sideB. 我想要的是选择元素之间的唯一链接,无论哪个元素是sideA或sideB。 For example, link between 100 and 200 is the same link as between 200 and 100, and only one record should be returned by query, something like: 例如,100到200之间的链接是200到100之间的相同链接,并且查询只返回一条记录,例如:

link_side_a_element_id | link_side_b_element_id
-----------------------------------------------
                   100 |                    200
                   300 |                    400

This will be enough for me. 这对我来说已经足够了。 But stuck on write proper select DML... Now I do it in Java, fetching all data to Set with proper hashCode() and equals() methods. 但坚持写正确选择DML ...现在我用Java做,用适当的hashCode()和equals()方法获取所有数据。 This is working for me for now, but want to get data right in SQL Management Studio... How to achieve this? 这对我来说现在很有用,但是想在SQL Management Studio中正确获取数据......如何实现这一目标?

Just pick an order that the two items should appear in (eg always list the lowest/earliest first) and then run a DISTINCT on that: 只需选择两个项目应该出现的顺序 (例如,始终列出最低/最早的第一个),然后运行DISTINCT

SELECT DISTINCT
   CASE WHEN link_side_a_element_id < link_side_b_element_id THEN link_side_a_element_id
        ELSE link_side_b_element_id END as a,
   CASE WHEN link_side_a_element_id < link_side_b_element_id THEN link_side_b_element_id
        ELSE link_side_a_element_id END as b
FROM
    table

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM