根据同一个表中的两个远程行选择第三列

时间:2018-04-26 17:44:45

标签: sql

我想根据同一个表中的两个远距离列选择第三列。

我只能想到这个:

select tl.thirdcolumn
from table1 t1
WHERE
EXISTS
(
    Select distinct tl.firstcolumn , t1.secondcolumn
    From t1
)

此:

select distinct tl.thirdcolumn
from table t1

不会起作用,因为我不想要明显的第三行。我希望第三行基于前两行是不同的。

我猜它是一种嵌套的sql语句,选择前1 ... idk

CATEGORY    NAME                             Query     
---------------------------------------------------
STUDENTS    NUMBER_OF_CHAPTERS               QueryA    
STUDENTS    NUMBER_OF_STUDENT_MEMBERS        QueryB    
STUDENTS    NUMBER_OF_STUDENT_MEMBERS        QueryB    
MEMBERS     NUMBER_OF_MEMBERS_WORLDWIDE      QueryC    
MEMBERS     NUMBER_OF_MEMBERS_WORLDWIDE      QueryC

2 个答案:

答案 0 :(得分:0)

  

查询 -

SELECT
    CATEGORY,NAME,QUERY
FROM
    (
        WITH TAB AS (
            SELECT
                'STUDENTS' AS CATEGORY,
                'NUMBER_OF_CHAPTERS' AS NAME,
                'QUERYA' AS QUERY
            FROM
                DUAL
            UNION ALL
            SELECT
                'STUDENTS' AS CATEGORY,
                'NUMBER_OF_STUDENT_MEMBERS' AS NAME,
                'QUERYB' AS QUERY
            FROM
                DUAL
            UNION ALL
            SELECT
                'STUDENTS' AS CATEGORY,
                'NUMBER_OF_STUDENT_MEMBERS' AS NAME,
                'QUERYB' AS QUERY
            FROM
                DUAL
            UNION ALL
            SELECT
                'MEMBERS' AS CATEGORY,
                'NUMBER_OF_MEMBERS_WORLDWIDE' AS NAME,
                'QUERYC' AS QUERY
            FROM
                DUAL
            UNION ALL
            SELECT
                'MEMBERS' AS CATEGORY,
                'NUMBER_OF_MEMBERS_WORLDWIDE' AS NAME,
                'QUERYC' AS QUERY
            FROM
                DUAL
        ) SELECT
            CATEGORY,
            NAME,
            QUERY,
            COUNT(*) OVER(PARTITION BY
                CATEGORY,
                NAME
                ORDER BY
                    CATEGORY,
                    NAME,
                    QUERY
            ) AS RNK
        FROM
            TAB
    )
WHERE
    RNK   = 1;
  

输出 -

"CATEGORY","NAME","QUERY"
"STUDENTS","NUMBER_OF_CHAPTERS","QueryA"

答案 1 :(得分:0)

您的问题很难理解,但我认为您可能只想要group by

select tl.firstcolumn , t1.secondcolumn, max(tl.thirdcolumn)
from table1 t1
group by tl.firstcolumn , t1.secondcolumn;

如果您想要一对值只显示一次的行,请添加having count(*) = 1

select tl.firstcolumn , t1.secondcolumn, max(tl.thirdcolumn)
from table1 t1
group by tl.firstcolumn , t1.secondcolumn
having count(*) = 1;