在一行中几乎没有条件的情况

时间:2016-08-08 08:59:21

标签: sql oracle

新编辑!

我想得到类似的东西:

ID1     DATE_1       DATE_2        DATE_3 
---     -------      -------       -------
99999 | 12-08-2016 | 14-08-2016 |  17-09-2016

但我明白了:

ID1     DATE_1     DATE_2      DATE_3
----    ------     --------    --------
99999 | 12-08-2016|           |
99999 |           | 14-08-2016|   
99999 |           |           | 17-09-2016

我的代码:

create table TABE1 as
select  
      A.ID1,
      max(CASE 
         WHEN A.ID2 IN (123,1234,12345,123456)  THEN A.CONATACTDATE
      END) AS DATA_1,

      max(CASE 
         WHEN A.ID2 IN (456,4567,45678,456789)  THEN A.CONATACTDATE
      END) AS DATA_2,

      max(CASE 
         WHEN A.ID2 IN (987,9876,98765,987654)  THEN A.CONATACTDATE
      END) AS DATA_3,   

      max(CASE 
         WHEN B.ID3 IN (1,2,3,4) THEN B.ID3
      END) AS ID_CC, 

      max(CASE 
         WHEN B.ID3 IN (1,2,3,4) THEN B.ID3
      END) AS ID_WW,

      max(CASE 
         WHEN B.ID3 IN (6,7,8,9) THEN B.ID3
      END) AS ID_CC2, 

      max(CASE 
         WHEN B.ID3 IN (6,7,8,9) THEN B.ID3
      END) AS ID_WW2
      from DATABASE1 A  LEFT JOIN 
      (SELECT ID1, ID2, ID3, FROM DATABASE2) B
      ON A.ID1=B.ID1
      WHERE A.ID2 IN (123,1234,12345,123456,456,4567,45678,456789,987,9876,98765,987654) 
      group by A.ID1,A.CONATACTDATE,B.ID3

ID1是人ID,ID2是该人的联系人ID(每个人至少联系一次,最多三次)

我将非常感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

使用group bymax即可实现:

....       
       A.id1, 
       Max(CASE 
             WHEN A.id2 IN ( 123, 1234, 12345, 123456 ) THEN A.contactdate 
           END) AS DATE_1, 
       Max(CASE 
             WHEN A.id2 IN ( 456, 4567, 45678, 456789 ) THEN A.contactdate 
           END) AS DATA_2, 
       Max(CASE 
             WHEN a.Id2 (987, 9876, 98765, 987654) THEN A.contactdate 
           END) AS DATA_3 
FROM   database1 A 
JOIN some table or something else
GROUP  BY A.id1 -- this is the last line.

答案 1 :(得分:0)

您永远无法获得此类输出(根据您的条件):

这是一个例子: 在case语句中使用ID2时。因为在单行中ID2只能有一个值。因此,如果值在(123,1234,12345,123456)中,那么只有您的第一个case语句会被命中,其他两个案例语句会失败,因此DATE_2DATE_3设置为{{1}导致类似的东西。

NULL

简单来说,只有你的case语句以这样的方式编写,只有一个会被命中,其他两个会为任何行返回NULL