2011-03-22 172 views
0

我有一張賬戶表和一個交易表。在報告中,我需要顯示每個帳戶的以下內容:有效獲取最小值,最大值和彙總數據

First Purchase Date, 
First Purchase Amount, 
Last Purchase Date, 
Last Purchase Amount, 
# of Purchases, 
Total of All Purchases. 

事務表看起來是這樣的:

TX_UID 
Card_Number 
Post_Date 
TX_Type 
TX_Amount 

目前我繼承查詢有一個子查詢每一種元素。在我看來,這應該是一種更有效的方式。我能夠使用存儲過程而不是單個查詢。

查詢的樣本來獲得所有交易的單一帳戶是:

select * from tx_table where card_number = '12345' and TX_Type = 'Purchase' 

任何想法?

回答

1

試試這個:

select tt1.post_date as first_purchase_date, 
     tt1.tx_amount as first_purchase_amount, 
     tt2.post_date as last_purchase_date, 
     tt2.tx_amount as last_purchase_amount, 
     tg.pc as purchase_count, 
     tg.amount as Total 
from (select Card_Number,min(post_date) as mipd, max(post_date) as mxpd, count(*) as pc, sum(TX_Amount) as Amount from tx_table where TX_Type = 'Purchase' group by card_number) tg 
join tx_table tt1 on tg.card_number=tt1.card_number and tg.mipd=tt1.post_date 
join tx_table tt2 on tg.card_number=tt2.card_number and tg.mxpd=tt2.post_date 
where TX_Type = 'Purchase' 

我加計..我沒看到它第一次。

如果您還需要關於多個TX_Types的摘要,則必須從where子句中將它取出,並將其放入組和內部選擇連接中。但我想你只需要購買

+0

謝謝!我能夠使用它作爲一個模型,它的工作很好。 – Erik 2011-03-22 19:26:58

0
;with cte as 
(
    select 
    Card_Number, 
    TX_Type, 
    Post_Date, 
    TX_Amount, 
    row_number() over(partition by TX_Type, Card_Number order by Post_Date asc) as FirstP, 
    row_number() over(partition by TX_Type, Card_Number order by Post_Date desc) as LastP 
    from tx_table 
) 
select 
    F.Post_Date as "First Purchase Date", 
    F.TX_Amount as "First Purchase Amount", 
    L.Post_Date as "Last Purchase Date", 
    L.TX_Amount as "Last Purchase Amount", 
    C.CC as "# of Purchases", 
    C.Amount as "Total of All Purchases" 
from (select Card_Number, TX_Type, count(*) as CC, sum(TX_Amount) as Amount 
     from cte 
     group by Card_Number, TX_Type) as C 
    inner join cte as F 
    on C.Card_Number = F.Card_Number and 
     C.TX_Type = F.TX_Type and 
     F.FirstP = 1  
    inner join cte as L 
    on C.Card_Number = L.Card_Number and 
     C.TX_Type = L.TX_Type and 
     L.LastP = 1 
相關問題