我想问一下如何编写这个SQL查询

时间:2017-12-12 20:45:49

标签: sql sql-server-2008 sum

我正在使用SQL Server 2008,我有三个表:

表1 帐户

Id >> auto number
AccountId
AccountName

表2 AccountsSupport

Id >> auto number
DateFrom
DateTo

在此表中我有一条记录,我将来不会添加任何记录

表3 AccTransD

Id >> auto number
TransId
TransDate
AccountId
AccountName
Value

我想这样查询:

SELECT 
    a.Id, a.AccountId, a.AccountName,  
    SUM(CASE WHEN b.TransDate < AccountsSuport.DateFrom THEN b.Value END) AS FirstVal, 
            SUM(CASE WHEN b.TransDate >= AccountsSuport.DateFrom AND b.TransDate <= AccountsSuport.DateTo THEN b.Value END) AS BetweenVal, 
            SUM(CASE WHEN b.TransDate > AccountsSuport.DateTo THEN b.Value END) AS LastVal, 

FROM
    dbo.Accounts AS a 
LEFT OUTER JOIN
    dbo.AccTransD AS b ON a.AccountId = b.AccountId 
GROUP BY 
    a.Id, a.AccountId, a.AccountName
ORDER BY 
    a.Id

示例数据:

Accounts:
Id  AccountId   AccountName
1   111            CashBox
2   222            VisaBox

表:TransD

Id  TransId    TransDate  AccountId     AccountName   Value
1     1          1/1/2017     111          cashbox     100
2     2          2/1/2017     222          visabox     200
3     2          2/2/2018     111          cashbox      50
4     7          1/1/2015     222          visabox      300

表:AccountsSupport: 有一个记录,我将来不会添加另一个     Id DateFrom DateTo     1 30/12/2016 30/12/2017

我的查询应该查看此

Id  AccountId  AccountName    FirstVal   betweenVal  LastVal
1      111       CashBox         0        100           50
2      222       VisaBox         300        200           0

1 个答案:

答案 0 :(得分:0)

您只需加入AccountsSupport即可。

{% load get_item from template_filters %}