Performance 高效地获取最小、最大和摘要数据

Performance 高效地获取最小、最大和摘要数据,performance,sql-server-2005,tsql,aggregate,Performance,Sql Server 2005,Tsql,Aggregate,我有一个账目表和一个交易表。在报告中,我需要为每个帐户显示以下内容: 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 目前,我继承的查询对每个元素都有一个子查询。在我看来

我有一个账目表和一个交易表。在报告中,我需要为每个帐户显示以下内容:

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'
有什么想法吗?

试试这个:

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_类型的摘要,则必须从where子句中获取它,并将其放入组和内部选择联接中。但我想您只需要购买

谢谢!我可以用它作为模型,它工作得很好。
;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