我想从Account_Transaction
表中提取过去4个月中超过两个学分的帐户的数据。我已经包含了示例数据以及我尝试过的SQL查询,但是没有提供我想要的数据:
SELECT DISTINCT
account_id
,transaction_type_id
,credit_amount
,effective_date
FROM Account_Transaction
WHERE transaction_type_id = 1
AND effective_date BETWEEN '01 feb 2015'
AND '01 may 2015'
GROUP BY account_id
HAVING COUNT(account_id) > 2
ORDER BY account_id
但这似乎无法获取所需的输出
答案 0 :(得分:0)
这应该有用......
SELECT DISTINCT
account_id
,transaction_type_id
,SUM(credit_amount)
,MAX(effective_date)
FROM Account_Transaction
WHERE transaction_type_id = 1
AND effective_date BETWEEN '01 feb 2015'
AND '01 may 2015'
GROUP BY account_id, transaction_type_id
HAVING COUNT(account_id) > 2
ORDER BY account_id
这将总结 credit_amount 并显示最后的 effective_date 。
如果您要列出符合上述条件的帐户的记录,您可以使用CTE ......
--the cte will give a list of Account ID's with the criteria
WITH cteAccounts AS (
SELECT DISTINCT
account_id
FROM Account_Transaction
WHERE transaction_type_id = 1
AND effective_date BETWEEN '01 feb 2015'
AND '01 may 2015'
GROUP BY account_id
HAVING COUNT(account_id) > 2
)
--join against the CTE to get the accounts Id's
SELECT a.account_id
,a.transaction_type_id
,a.credit_amount
,a.effective_date
FROM Account_Transaction a INNER JOIN cteAccounts b on a.account_id = b.account_id
WHERE a.transaction_type_id = 1
AND a.effective_date BETWEEN '01 feb 2015'
AND '01 may 2015'
ORDER BY account_id