是否可以将多个select语句映射到列中?

时间:2015-07-24 07:55:24

标签: sql oracle oracle11g

我有这张桌子:

code(integer) |number_of_data(integer)| date (Date)

我需要:

  1. 按天分组,仅适用于6月的那个月
  2. 为每个代码选择当天number_of_data的总和!= 0
  3. 为代码选择n_data = 0
  4. 对于我提出的前两点:

    select sum(number_of_data) nData, TO_CHAR(date, 'DD') dayOfMonth from T1 
    where to_char( date, 'mm') = 6 
     and code <> 0
     group by TO_CHAR(date, 'DD') order by TO_CHAR(date, 'DD');
    

    它给了我这个表结果:

    nData | dayOfMonth
    

    这很好,无论如何我缺少要求3,其查询将是相同但具有相反的条件(代码= 0)。 有没有办法将其添加到上面的查询,以获得此结果:

    nData | nDataZero | dayOfMonth
    

3 个答案:

答案 0 :(得分:1)

对MS Sql中的语法提出一些看法。这是我用oracle sql方式解决这个问题的方法:)

SELECT sum(nData) nData , sum(nDataZero) nDataZero, T1 
from (
select sum(number_of_data) nData, 0 nDataZero , TO_CHAR(date, 'DD') dayOfMonth 
from T1 
where to_char( date, 'mm') = 6  and code <> 0  
group by TO_CHAR(date, 'DD') 
order by TO_CHAR(date, 'DD') 
UNION 
select 0 nData, sum(number_of_data) nDataZero , TO_CHAR(date, 'DD') dayOfMonth 
from T1 
where to_char( date, 'mm') = 6 and code == 0 
group by TO_CHAR(date, 'DD') 
order by TO_CHAR(date, 'DD')) 
group by T1;

RGDS

答案 1 :(得分:0)

您可以使用CASE将数据分成2个插槽,代码= 0,代码&lt;&gt; 0:

select sum(number_of_data) nData, TO_CHAR(date, 'DD') dayOfMonth, CASE WHEN code = 0 THEN 0 ELSE 1 AS x  
from T1 
where to_char( date, 'mm') = 6 
group by TO_CHAR(date, 'DD'), x 
order by TO_CHAR(date, 'DD');

答案 2 :(得分:0)

假设每天只有一个CODE = 0条目,那么你可以这样做:

SELECT SUM( CASE CODE WHEN 0 THEN NULL ELSE number_of_data END ) AS nData,
       MAX( CASE CODE WHEN 0 THEN number_of_data END ) AS nDataZero,
       EXTRACT( DAY FROM "Date" ) AS dayOfMonth
FROM   T1 
WHERE  EXTRACT( MONTH FROM "Date" ) = 6 
GROUP BY EXTRACT( DAY FROM "Date" )
ORDER BY EXTRACT( DAY FROM "Date" );

如果有多个条目,那么您需要指定如何处理(例如,如果您想要MAX值的总和,请将SUM更改为CODE = 0 )。