如何在Oracle查询中放入IF ELSE CONDITION?

时间:2018-04-24 10:15:43

标签: sql oracle greatest-n-per-group

我有一张桌子,A和B,如下所示,

表 答:

  • ID
  • idB前
  • 名称
  • 教师

B:

  • ID
  • 名称

表B有2条记录如下。

SELECT *
FROM B;

 1, 1, 'First'
 2, 2, 'Second'

表A有8条记录如下。

SELECT *
FROM A;

 1, 1, A, IT
 2, 1, B, IT
 3, 1, C, IT
 4, 1, D, Medicine
 5, 1, E, Medicine
 6, 1, F, Business
 7, 1, G, Business
 8, 1, H, IT

 9, 2, A, Medicine
 10, 2, B, Medicine
 11, 2, C, Medicine
 12, 2, D, Medicine
 13, 2, E, Medicine
 14, 2, F, Medicine
 15, 2, G, Business
 16, 2, H, Medicine

我的问题是:

如何从表B中选择教师应该是IT的数据,如果有多个,则应该使用最大ID。如果没有任何IT,应该开展业务吗?

我的选择视图应如下所示:

A和B记录。

  1. 8, 1 ,H,IT,首先
  2. 15, 2 ,G,商业,第二
  3. 请问您能以哪种方式提供这些数据的建议和帮助?

3 个答案:

答案 0 :(得分:1)

SELECT A.*,T.Name
FROM 
TableA A
INNER JOIN
(
SELECT MAX(A.id) AS id,A.FACULTY,B.NAME,
  ROW_NUMBER() OVER (PARTITION BY B.NAME ORDER BY MAX(A.id) DESC) AS RN FROM TableA A
INNER JOIN TableB B
ON A.idB=B.id
WHERE faculty IN ('IT', 'Business')
GROUP BY A.FACULTY,B.NAME
) T
ON A.id = T.id
AND A.FACULTY = T.FACULTY
WHERE T.RN=1

<强>输出

ID  IDB  NAME   FACULTY   NAME
8   1    H      IT        First
15  2    G      Business  Second

<强>演示

  

http://sqlfiddle.com/#!4/98b84/24

答案 1 :(得分:1)

此查询将帮助您获得所需的结果

SELECT id
    ,name
    ,faculty
FROM A
WHERE faculty IN ('IT', 'Business')

答案 2 :(得分:1)

  

如何从表B中选择教师应该是IT的数据,如果有多个,则应该使用最大ID。如果没有任何IT,应该开展业务吗?

这将获得IT中最大ID的行,如果没有IT行,则Business

SELECT *
FROM   (
  SELECT A.id,
         A.idB,
         A.name,
         A.faculty,
         B.name AS bname
  FROM   A
         INNER JOIN B
         ON ( A.idB = B.id )
  WHERE  A.faculty IN ( 'IT', 'Business' )
  ORDER BY
         DECODE( A.faculty, 'IT', 1, 'Business', 2 ),
         A.id DESC
)
WHERE  ROWNUM = 1;

如果您想要每组的第一行:

SELECT id,
       idB,
       name,
       faculty,
       bname
FROM   (
  SELECT A.id,
         A.idB,
         A.name,
         A.faculty,
         B.name AS bname,
         ROW_NUMBER() OVER (
           PARTITION BY A.faculty
           ORDER BY     A.id DESC
         ) AS rn
  FROM   A
         INNER JOIN B
         ON ( A.idB = B.id )
  WHERE  A.faculty IN ( 'IT', 'Business' )
)
WHERE  rn = 1;