我有这张桌子:
code(integer) |number_of_data(integer)| date (Date)
我需要:
对于我提出的前两点:
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
答案 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
)。