如何计算给定条件下的列数?

时间:2015-12-14 08:47:28

标签: sql oracle count

我有以下查询导致以下输出:

select file_name, 
       count(account_number) as account_count
  from tbl_account_detail 
 group by file_name;

-------------------------------------------------------
        FILE_NAME       |  CUR_DATE   |  ACCOUNT_COUNT
-------------------------------------------------------
 20151124_99999_101.xml |  05-DEC-15  |     499
 20151124_99999_102.xml |  05-DEC-15  |     500
 20151124_99999_103.xml |  05-DEC-15  |     500
 20151124_99999_104.xml |  05-DEC-15  |     499
 20151124_99999_105.xml |  05-DEC-15  |     500
 20151124_99999_107.xml |  05-DEC-15  |     500

但我想根据列history_flag计算帐号,该列也包含值0,1,2和group,结果应该像

------------------------------------------------------------------------------------
         FILE_NAME      |  CUR_DATE   | P_account(0) | H_account(1) | h1_account(2)
------------------------------------------------------------------------------------
 20151124_99999_101.xml |  05-DEC-15  |     400      |      50      |      20
 20151124_99999_102.xml |  05-DEC-15  |      50      |     300      |     100
 20151124_99999_103.xml |  05-DEC-15  |      50      |     200      |     100
 20151124_99999_104.xml |  05-DEC-15  |      49      |     100      |     100
 20151124_99999_105.xml |  05-DEC-15  |      50      |     100      |     100
 20151124_99999_107.xml |  05-DEC-15  |      50      |     100      |     100

因为帐户有一个标志,决定它是生产帐户还是历史帐户。我怎样才能实现这样的count(account_number) as p_account(0), count(account_number) as H1_account(1), count(account_number) as H2_account_number

TBL_ACCOUNT_DETAIL的内容:

------------------------------------------------------------
 ACCOUNT_NUMBER  |          FILE_NAME       |  HISTORY_FLAG
------------------------------------------------------------
 00011140107315  |  20151124_99999_104.xml  |       0
 00011140104490  |  20151124_99999_104.xml  |       1
 00011140108151  |  20151124_99999_104.xml  |       0
 00011140108161  |  20151124_99999_104.xml  |       0
 00532050000039  |  20130605_99999_233.xml  |       0

2 个答案:

答案 0 :(得分:1)

您可以使用CASE表达式进行条件计数:

select file_name,
       count(account_number) as account_count,
       sum(case when history_flag = 0 then 1 end) as hist_0,
       sum(case when history_flag = 1 then 1 end) as hist_1,
       sum(case when history_flag = 2 then 1 end) as hist_2
from tbl_account_detail 
group by file_name

答案 1 :(得分:0)

你可以试试这个:

select distinct file_name, count(1) over (partition by file_name) as account_count,
count(1) over (partition by <second_column>) as <second_alias>
from tbl_account_detail;

它被称为分析函数,您可以应用许多聚合函数,如rank(),row_number(),sum(),min(),max(),avg()等。