简体   繁体   English

通过T-SQL从表数据中查询数据

[英]Requiering data trieve from the table data by T-SQL

在此处输入图片说明

I want to extract data from the Account_Transaction table for accounts with more than two credits in the last 4 months. 我想从Account_Transaction表中提取过去4个月中拥有两个以上信用的帐户的数据。 I have included sample data along with a SQL query I have tried, but does not provide the data I want: 我已经提供了示例数据以及我尝试过的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   

but this seems doesn't fetch the desired output 但这似乎无法获取所需的输出

This should work... 这应该工作...

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

This will sum up the credit_amount and show the last effective_date . 这将汇总credit_amount并显示最后一个有效日期

If you want to list the records for the account that meets the above criteria, you could use a CTE... 如果要列出符合上述条件的帐户的记录,则可以使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM