使用日期条件和GROUP BY的DSum

时间:2013-11-19 10:37:13

标签: sql ms-access select group-by sum

我想写一个访问查询(我认为SQL最合适),以便为每个产品检索单个数字或数字总和,如果这些数字绑定到相似的日期。

我的表格如下:

Tck1    DeD1    Bdf1
Tck1    DeD2    Bdf2
Tck1    DeD3    Bdf3
Tck2    DeD1    Bdf1
Tck2    DeD1    Bdf2
Tck2    DeD1    Bdf3
Tck2    DeD2    Bdf4
Tck3    DeD1    Bdf1
Tck3    DeD2    Bdf2

正如你所看到的,对于Tck1和Tck2我只需要检索Bdf1但是对于Tck2我需要求和Bdf1,Bdf2和Bdf3

我尝试了一些陈述(不成功):

SELECT Sum([tblB].Bdf) As SumOfBdf
FROM [tblB]
GROUP BY Tck
HAVING (DeD = Min(Ded));

以及:

SELECT Sum([tblB].Bdf) As Expr1
FROM [tblB]
GROUP BY Tck
HAVING (DeD = Min(Ded));

知道我应该更改什么来提取数据?感谢

感谢给所有看过它的人,特别是戈德。

以下是单一陈述中的答案:

SELECT tblB.Tck, tblB.DeD, Sum(tblB.Bdf) AS SumOfBdf
FROM tblB
GROUP BY tblB.Tck, tblB.DeD
HAVING (((tblB.DeD) In (SELECT Min(tblB.DeD) AS MinOfDeD FROM tblB GROUP BY tblB.Tck;)));

1 个答案:

答案 0 :(得分:1)

假设您的数据如下所示:

ID  Tck   DeD         Bdf
--  ----  ----------  ---
 1  Tck1  2013-01-01  100
 2  Tck1  2013-01-02  101
 3  Tck1  2013-01-03  102
 4  Tck2  2013-02-01  201
 5  Tck2  2013-02-01  202
 6  Tck2  2013-02-01  203
 7  Tck2  2013-02-02  204
 8  Tck3  2013-03-01  301
 9  Tck3  2013-03-02  302

然后,返回每个[Tck]的最早日期的查询将是

SELECT Tck, Min(DeD) AS MinOfDeD FROM tblB GROUP BY Tck

这给了我们

Tck   MinOfDeD  
----  ----------
Tck1  2013-01-01
Tck2  2013-02-01
Tck3  2013-03-01

下一步是将该查询用作子查询以隔离属于这些日期的行

SELECT tblB.Tck, tblB.DeD, tblB.Bdf
FROM
    tblB
    INNER JOIN
    (
        SELECT Tck, Min(DeD) AS MinOfDeD FROM tblB GROUP BY Tck
    ) AS minDates
        ON tblB.Tck = minDates.Tck AND tblB.DeD = minDates.MinOfDeD

返回

Tck   DeD         Bdf
----  ----------  ---
Tck1  2013-01-01  100
Tck2  2013-02-01  201
Tck2  2013-02-01  202
Tck2  2013-02-01  203
Tck3  2013-03-01  301

最后,我们可以将它包装在聚合查询中,以便为我们提供总和

SELECT Tck, DeD, Sum(Bdf) AS SumOfBdf
FROM
    (
        SELECT tblB.Tck, tblB.DeD, tblB.Bdf
        FROM
            tblB
            INNER JOIN
            (
                SELECT Tck, Min(DeD) AS MinOfDeD FROM tblB GROUP BY Tck
            ) AS minDates
                ON tblB.Tck = minDates.Tck AND tblB.DeD = minDates.MinOfDeD
    )
GROUP BY Tck, DeD

返回

Tck   DeD         SumOfBdf
----  ----------  --------
Tck1  2013-01-01       100
Tck2  2013-02-01       606
Tck3  2013-03-01       301

编辑重新评论

如果我们稍微调整测试数据:

ID  Tck   DeD         Bdf
--  ----  ----------  ---
 1  Tck1  2013-01-01  100
 2  Tck1  2013-01-02  101
 3  Tck1  2013-01-03  102
 4  Tck2  2013-01-02  201

然后是评论中的查询(和更新后的问题)

SELECT tblB.Tck, tblB.DeD, Sum(tblB.Bdf) AS SumOfBdf 
FROM tblB 
GROUP BY tblB.Tck, tblB.DeD 
HAVING (((tblB.DeD) In (SELECT Min(tblB.DeD) AS MinOfDeD FROM tblB GROUP BY tblB.Tck;)));

为'Tck1'

返回两行
Tck   DeD         SumOfBdf
----  ----------  --------
Tck1  2013-01-01       100
Tck1  2013-01-02       101
Tck2  2013-01-02       201

因为HAVING子句不区分Min(日期)[Tck]

我在这个编辑上面的答案中的最后一个查询( 提供“一个查询”中的解决方案,虽然它使用了一些子查询),返回

Tck   DeD         SumOfBdf
----  ----------  --------
Tck1  2013-01-01       100
Tck2  2013-01-02       201