簡體   English   中英

通過T-SQL從表數據中查詢數據

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

在此處輸入圖片說明

我想從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   

但這似乎無法獲取所需的輸出

這應該工作...

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並顯示最后一個有效日期

如果要列出符合上述條件的帳戶的記錄,則可以使用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