以列方式显示输出

时间:2014-03-21 12:31:01

标签: sql

我在查询下运行。

select to_char(cdts,'HH24'), count(id)) from tbl_log where acmd = 'Add' and trunc(cdts) = trunc(sysdate -1) and astat = '14'
group by to_char(cdts, 'HH24')
order by to_char(cdts, 'HH24')

输出结果为:

Hours   Count
01  1
04  1
07  1
08  4
09  41
10  174
11  91
12  220
13  241
14  195
15  228
16  221
17  185
18  20
19  15
20  8
21  4
22  4
23  1

同样,我想尝试以下格式。任何人都可以帮助我们如何获得相同的。 基本上,当我尝试sysdat -3 ..它是行明智的..但我想按日期分组..

Hours   21st March  20th March  19th March
01  1   0   0
04  1   1   2
07  1   4   10
08  4   24  16
09  41  16  84
10  174 18  106
11  91  18  140
12  220 96  170
13  241 146 152
14  195 127 178
15  228 123 225
16  221 110 168
17  185 13  30
18  20  13  4
19  15  19  11
20  8   3   3
21  4   0   0
22  4   0   0
23  1   0   0

1 个答案:

答案 0 :(得分:0)

以下是我为项目准备的一个查询,您可以使用相同的逻辑。希望它对您有所帮助。

;With CTE as 
(
    select  Hours
        ,tDateDay
        ,Cnt
)
select Hours,
    Isnull([1],0) as dt1,Isnull([2],0) as dt2,Isnull([3],0) as dt3,Isnull([4],0) as dt4,Isnull([5],0) as dt5,
    Isnull([6],0) as dt6,Isnull([7],0) as dt7,Isnull([8],0) as dt8,Isnull([9],0) as dt9,Isnull([10],0) as dt10,
    Isnull([11],0) as dt11,Isnull([12],0) as dt12,Isnull([13],0) as dt13,Isnull([14],0) as dt14,Isnull([15],0) as dt15,
    Isnull([16],0) as dt16,Isnull([17],0) as dt17,Isnull([18],0) as dt18,Isnull([19],0) as dt19,Isnull([20],0) as dt20,
    Isnull([21],0) as dt21,Isnull([22],0) as dt22,Isnull([23],0) as dt23,Isnull([24],0) as dt24,Isnull([25],0) as dt25,
    Isnull([26],0) as dt26,Isnull([27],0) as dt27,Isnull([28],0) as dt28,Isnull([29],0) as dt29,Isnull([30],0) as dt30,
    Isnull([31],0) as dt31
 from CTE
pivot (sum(Cnt) for tDateDay in([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],
[20],[21],[22],[23],[24],[25],[26],[27],[28],[29],[30],[31])) as DayDate 
order by Hours asc