对一个子表有多个计数的sql

时间:2011-03-04 16:38:46

标签: sql db2

DB2数据库。请求可以有多个事务。我想查询请求并获取不同事务类型的计数。因此,请求1具有四个交易(AA,BB,BB,CC)将导致: REQ = 1234,REQ_USER ='Susan',REQ_ACCT = 223344,CNT_AA = 1,CNT_BB = 2,CNT_CC = 3

此查询可以准确计算一种交易类型:

SELECT COUNT(*) AS TRANS_AA
FROM TABLE1 AS T1, TABLE2 AS T2
WHERE T1.REQUEST_ID=1234 
AND T1.COMPONENTID = T2.PARENTCOMPID
AND T2.TRANS_TYPE='AA';

如果我也想要请求ID,这个查询给了我但我需要'分组依据'请求ID:

SELECT T1.REQUEST_ID, COUNT(*) AS TRANS_AA
FROM TABLE1 AS T1, TABLE2 AS T2
WHERE T1.REQUEST_ID=1234 
AND T1.COMPONENTID = T2.PARENTCOMPID
AND T2.TRANS_TYPE='AA'
GROUP BY T1.REQUEST_ID;

我不确定如何从T1(用户,帐户等)添加多个列以及几种事务类型(假设我们有10种不同的类型)。我已经在两者之间尝试了一些INNER JOIN,但我不确定这是否可以有效地完成,或者一个JOIN用于所有计数,或多个连接等等。

我发布了一些我想要回复的数据样本,但是根据以下要求。

TABLE1
componentid (key)
request_id
req_user
req_account
... 27 more columns

TABLE 2 (child table, could have many trans_types for T1)
parentcompid (foreign key to componentid in Table1)
trans_type

1 个答案:

答案 0 :(得分:0)

您可以使用DB2的WINDOW函数来实现此目的。

您可以将现有查询重写为:

SELECT T1.REQUEST_ID, COUNT(1) OVER(PARTITION BY T1.REQUEST_ID) AS TRANS_ABC 
  FROM TABLE1 AS T1, TABLE2 AS T2 
 WHERE T1.REQUEST_ID=1234  
   AND T1.COMPONENTID = T2.PARENTCOMPID 
     AND T2.TRANS_TYPE='ABC' 

使用窗口功能时,可以使用选择列表中的任何列。 请查看以下链接以获取更多信息:

http://publib.boulder.ibm.com/infocenter/db2luw/v9/index.jsp?topic=/com.ibm.db2.udb.admin.doc/doc/r0023461.htm

如果您想要数据透视,我不确定DB2是否本身支持PIVOT / UNPIVOT。 这是我能构建的最好的(不确定性能但是没有测试查询):

注意:此查询考虑了6种不同类型的trans_types。如果Trans_Type不是有限的,那么我不确定是否会有任何简单的解决方案。

SELECT *
  FROM (
                SELECT  t1.request_id, 
                                t1.req_user, 
                                t1.req_acct, 
                                SUM(DECODE(trans_type, 'AA',1, 0)) OVER(PARTITION BY t1.request_id) AS trans_aa, 
                                SUM(DECODE(trans_type, 'BB',1, 0)) OVER(PARTITION BY t1.request_id) AS trans_bb, 
                                SUM(DECODE(trans_type, 'CC',1, 0)) OVER(PARTITION BY t1.request_id) AS trans_cc, 
                                SUM(DECODE(trans_type, 'DD',1, 0)) OVER(PARTITION BY t1.request_id) AS trans_dd, 
                                SUM(DECODE(trans_type, 'EE',1, 0)) OVER(PARTITION BY t1.request_id) AS trans_ee, 
                                SUM(DECODE(trans_type, 'FF',1, 0)) OVER(PARTITION BY t1.request_id) AS trans_ff,
                                        SUM(1) AS total_trans
                                ROW_NUMBER() OVER(PARTITION BY t1.request_id) AS rn
                FROM TABLE1 AS t1, TABLE2 AS t2
                WHERE t1.request_id=1234 AND t1.componentid = t2.parentcompid
            ) a
 WHERE rn = 1