我想编写一个SQL,它给我的ouptut如下:
Elements Elements/total Elements/total2 Elements/total3
Books 6
Books Science 3
Books Arts 3
Books Science 1st Year 1
Books Science 2nd Year 1
Books Science 3rd Year 1
Books Arts 1st Year 1
Books Arts 2nd Year 1
Books Arts 3rd Year 1
我的表Books_table:
Books Stream Year
Book1 Science 1
Book2 Science 2
Book3 Science 3
Book4 Arts 1
Book5 Arts 2
Book6 Arts 3
请帮我看看如何编写查询。
答案 0 :(得分:0)
您想要的是Oracle的GROUP BY ROLLUP
功能。
它是GROUP BY
的扩展,为每个组添加了一个额外的行,包含小计。 (查看docs
ROLLUP
将小计后的行放在小组之后,您希望它位于查询的顶部,因此我添加了一些排序。
在我的查询中,我还使用DECODE
将年份编号转换为您指定的可读格式,
select Stream, DECODE(Year, 1, '1st year', 2, '2nd year', 3, '3rd year', null, null, Year || 'th year') as "Year_text", count(*)
from books
group by rollup(Stream, Year)
order by nvl2(year, '2', '1'), Stream NULLS First, Year