组上的SQL聚合

时间:2015-02-19 22:04:41

标签: sql sql-server

我是SQL的新手,我被困住了。我编写了一个查询,返回个人进行的交易列表,每个人都拥有一个唯一的ID号-PARENTACCOUNT。我想根据他们所做的交易次数将这些个人分成几组(例如,0个交易,1-2个交易,3-4个交易等)。然后我想计算个人数并计算每个组的平均交易金额。以下是产生事务列表的查询:

SELECT DISTINCT st.BALANCECHANGE
    ,st.PARENTACCOUNT
    ,s.ID
    ,st.SEQUENCENUMBER
    ,st.POSTDATE
FROM dbo.ACCOUNT AS a
    JOIN dbo.SAVINGSTRANSACTION AS st
        ON a.ACCOUNTNUMBER = st.PARENTACCOUNT
    JOIN dbo.CARD AS c
        ON st.PARENTACCOUNT = c.PARENTACCOUNT
            AND a.ProcessDate = st.ProcessDate
    JOIN dbo.SAVINGS AS s
        ON st.PARENTACCOUNT = s.PARENTACCOUNT
            AND s.ID = st.PARENTID
            AND s.ProcessDate = a.ProcessDate
            AND s.PARENTACCOUNT = a.ACCOUNTNUMBER
WHERE a.ProcessDate >= (SELECT MAX(ACCOUNT.ProcessDate) FROM ACCOUNT)
    AND a.TYPE <= 2
    AND s.CLOSEDATE IS NULL
    AND s.SHARECODE = 1
    AND (c.TYPE = 15 OR c.TYPE = 16)
    AND c.EXPIRATIONDATE > GETDATE()
    AND c.STATUS = 1
    AND st.SOURCECODE = 'O'
    AND st.VOIDCODE = 0
    AND st.POSTDATE >= (DATEADD(m,-1,DATEADD(mm,DATEDIFF(m,0,GETDATE()),0)))
    AND st.POSTDATE <=(DATEADD(D,-1,DATEADD(mm,DATEDIFF(m,0,GETDATE()),0)))

所以我想按事务组进行分组,并在组上执行聚合命令。任何帮助将不胜感激。

0 个答案:

没有答案