Oracle sql --SUbquery编写差异

时间:2013-08-12 13:44:10

标签: sql oracle oracle11g

我有两个表格表1和表格2,共同列为lead_no

现在我想显示表1中的数据

如果月份差异为6,则显示列名称为6,如果月份差异为 5然后coumn名称变为5,依此类推,直到月份差异等于1.有趣的是,列值应该是根据某些where条件从表2中获取的特定列名称的行数。我将在最后列出这些条件。

months_diff与桌面2的SYSTATE和reported_date列不同。

Where conditions


SELECT  col1 as 1  , col2 as 2, col 3 as ... col6 as 6 
  FROM   table1 a
 WHERE   lead_no not in   (SELECT   LEAD_NO FROM table2 
and  RPTCODE=101 and
round(months_between(sysdate,REPORTED_DATE)) NOT IN (1,2,3,4,5,6)
)

);

这里的主要问题是执行子查询以上述格式显示数据。如果发布的问题不够明确,请告诉我。

2 个答案:

答案 0 :(得分:0)

你正在寻找某种支点。因为你还没有写过你正在尝试的版本

select  sum(case when round(months_between(sysdate,reported_date)) = 1 then 1 else 0 end) as m1 , 
        sum(case when round(months_between(sysdate,reported_date)) = 2 then 1 else 0 end) as m2 , 
        sum(case when round(months_between(sysdate,reported_date)) = 3 then 1 else 0 end) as m3 , 
        sum(case when round(months_between(sysdate,reported_date)) = 4 then 1 else 0 end) as m4 , 
        sum(case when round(months_between(sysdate,reported_date)) = 5 then 1 else 0 end) as m5 , 
        sum(case when round(months_between(sysdate,reported_date)) = 6 then 1 else 0 end) as m6 , 
        count(*) as m_all
from    table1 a , table2 b
where   a.lead_no = b.lead_no
and     rptcode <> 101

我无法理解分组的内容,但您可以将其添加进去。

答案 1 :(得分:0)

SELECT  
  sum(CASE round(months_between(sysdate,REPORTED_DATE) WHEN 1 THEN 1 ELSE 0 END ) as 1  
, sum(CASE round(months_between(sysdate,REPORTED_DATE) WHEN 2 THEN 1 ELSE 0 END ) as 2  
, sum(CASE round(months_between(sysdate,REPORTED_DATE) WHEN 3 THEN 1 ELSE 0 END ) as 3  
, sum(CASE round(months_between(sysdate,REPORTED_DATE) WHEN 4 THEN 1 ELSE 0 END ) as 4  
, sum(CASE round(months_between(sysdate,REPORTED_DATE) WHEN 5 THEN 1 ELSE 0 END ) as 5  
, sum(CASE round(months_between(sysdate,REPORTED_DATE) WHEN 6 THEN 1 ELSE 0 END ) as 6  
  FROM   table1 a
WHERE   lead_no not in   (SELECT   LEAD_NO 
                          FROM table2 
                          WHERE
                            RPTCODE=101 
                          and round(months_between(sysdate,REPORTED_DATE)) NOT IN (1,2,3,4,5,6)
                         )
;