SQL选择不同但详尽的列

时间:2016-03-02 08:46:07

标签: mysql sql

我有一个包含2列的简单表:

Col1 | Col2
-----+-----
1    | 3
1    | 4
2    | 3
2    | 4
... many more rows

我想要归还:

Col1 | Col2
-----+-----
1    | 3
2    | 4

我不想要这个:

Col1 | Col2
-----+-----
1    | 3
2    | 3

因为3在Col2中重复,而且

Col1 | Col2
-----+-----
1    | 3
1    | 4

因为1在Col1中重复,而且

Col1 | Col2
-----+----
1    | 3

因为Col2中现在缺少4个。换句话说,我不想要重复,但我也不想省略col2中的任何值(除非它在Col1中出现重复 - 反之亦然)。我如何使用SQL来做我想要的?感谢。

2 个答案:

答案 0 :(得分:0)

根据您给定的样本数据进行工作

select col1,
case
when col1 =1 and col2 in (3,4) Then 3
when col1 =2 and col2 in (3,4) Then 4
end as col2
from table1
group by col1

有关详细信息,请转到此处sql fiddle

答案 1 :(得分:0)

我认为您需要这样的查询:

<mvc:View
        xmlns="sap.m"
        xmlns:html="http://www.w3.org/1999/xhtml"
        xmlns:mvc="sap.ui.core.mvc">

    <html:ul class="topMenu">
        <html:li>
            <Button class="linkButton providerReservation" text="{i18n>homePageLinks1}"></Button>
        </html:li>
        <html:li>
            <Button class="linkButton" text="{i18n>homePageLinks2}"></Button>
        </html:li>
        <html:li>
            <Button class="linkButton" text="{i18n>homePageLinks3}"></Button>
        </html:li>
        <html:li>
            <Button class="linkButton" text="{i18n>homePageLinks4}"></Button>
        </html:li>
        <html:li>
            <Button class="linkButton materData" text="{i18n>homePageLinks5}"></Button>
        </html:li>
        <html:li>
            <Button class="linkButton" text="{i18n>homePageLinks6}"></Button>
        </html:li>
        <html:li>
            <Button class="linkButton" text="{i18n>homePageLinks7}"></Button>
        </html:li>
    </html:ul>
</mvc:View>
  1. 您需要具有行号的SELECT Col1, Col2 FROM (SELECT dt.*, @rownum1 := @rownum1 + 1 AS rn FROM (SELECT Col1 FROM t GROUP BY Col1) dt, (SELECT @rownum1 := 0) r) t1 LEFT OUTER JOIN (SELECT dt.*, @rownum2 := @rownum2 + 1 AS rn FROM (SELECT Col2 FROM t GROUP BY Col2) dt, (SELECT @rownum2 := 0) r) t2 ON t1.rn = t2.rn UNION ALL SELECT Col1, Col2 FROM (SELECT dt.*, @rownum3 := @rownum3 + 1 AS rn FROM (SELECT Col2 FROM t GROUP BY Col2) dt, (SELECT @rownum3 := 0) r) t1 LEFT OUTER JOIN (SELECT dt.*, @rownum4 := @rownum4 + 1 AS rn FROM (SELECT Col1 FROM t GROUP BY Col1) dt, (SELECT @rownum4 := 0) r) t2 WHERE (t2.Col1 IS NULL); 的不同值。
  2. 您还需要具有行号的Col1的不同值。
  3. 现在,您可以使用Col2FULL OUTER JOIN行号进行UNION ALL设置ON
  4. [SQL Fiddle Demo]