列到行

时间:2014-09-09 10:02:10

标签: sql oracle

我有一个要求是显示一个月的总天数和星期天的月份数,如下所示。

总天数:30 星期日:4

请帮帮我..

我试过以下查询..

WITH total_days AS
(
    SELECT  to_char(last_day(sysdate),'dd') total,
            (select trunc((last_day(trunc(sysdate))-(trunc(sysdate,'mm'))+1)/7) from dual) Sunday,
            1 no
    FROM Dual
)
SELECT  total,
        sunday
FROM    total_days td
pivot
(
    count(1)
    FOR no in(1)
);

请帮帮我..

非常感谢你的帮助。

我正在使用oracle 11g版本......

1 个答案:

答案 0 :(得分:2)

查询1:

/* A CTE with all days in current month */
with current_month_days as
(
  select trunc(sysdate,'MON')+level-1 as my_date
  from dual
  connect by level <= to_char(last_day(sysdate),'DD')
)
select count(1) as total_days,
       count(decode(TO_CHAR(my_date,'DY'),'SUN',1)) as "Sundays"
FROM current_month_days;

<强>结果:

TOTAL_DAYS    Sundays
---------- ----------
        30          4

这就是所有的日子!

查询2:

with current_month_days as
(
  select trunc(sysdate,'MON')+level-1 as my_date 
   from dual
  connect by level <= to_char(last_day(sysdate),'DD')
)
select NVL(TO_CHAR(my_date,'DAY'),'TOTAL') as day,
        count(1)
FROM current_month_days
GROUP BY ROLLUP(TO_CHAR(my_date,'DAY'));

<强>结果:

DAY                                    COUNT(1)
------------------------------------ ----------
FRIDAY                                        4
MONDAY                                        5
SATURDAY                                      4
SUNDAY                                        4
THURSDAY                                      4
TUESDAY                                       5
WEDNESDAY                                     4
TOTAL                                        30

SQL Fiddle Demo

请求格式为OP:

/* A CTE with all days in current month */
with current_month_days as
(
  select trunc(sysdate,'MON')+level-1 as my_date
  from dual
  connect by level <= to_char(last_day(sysdate),'DD')
)
select 'Total Days : '||count(1) ||'   Sundays :'||
       count(decode(TO_CHAR(my_date,'DY'),'SUN',1)) as "Result"
FROM current_month_days;

<强>结果:

Result
--------------------------------------------------------------------------------
Total Days : 30   Sundays :4