基于日期的总和列

时间:2018-08-29 20:55:40

标签: sql sum firebird interbase

我有一张桌子,但是我将不得不根据Docdate列求和总计。我正在使用Firebird Interbase。我已经尝试了以下方法,但是似乎看不到我在做什么错。任何建议都将不胜感激。

我的查询仅返回我自己的结果,而未汇总购买列:

DOCTYPE DESCRIPTION STUDENTID   DOCDATE VOUCHERDATE DOCNUMB PURCHASES   NAME    TOTAL
1   800130-EE20180810   800130  8/04/2018   8/04/2018   800130-EE20180810   2.99        
1   800130-EE20180810   800130  8/04/2018   8/04/2018   800130-EE20180810   5.39        
1   800130-EE20180810   800130  8/04/2018   8/04/2018   800130-EE20180810   1.03        
1   800130-EE20150810   800130  7/24/2015   7/24/2015   800130-EE20150810   8.99        
1   800130-EE20150810   800130  7/24/2015   7/24/2015   800130-EE20150810   15.32       
1   800130-EE20150810   800130  7/24/2015   7/24/2015   800130-EE20150810   2.93        

预期结果:

DOCTYPE DESCRIPTION STUDENTID   DOCDATE VOUCHERDATE DOCNUMB PURCHASES   NAME    TOTAL
1   800130-EE20180810   800130  8/04/2018   8/04/2018   800130-EE20180810   9.41
1   800130-EE20150810   800130  7/24/2015   7/24/2015   800130-EE20150810   27.24           

我的查询

SELECT DISTINCT
  '1' AS DOCTYPE
 ,DESCRIPTION
    ,STUDENTID
    ,DOCDATE
    ,VOUCHERDATE
    ,DOCNUMB
    ,PURCHASES
    ,NAME
    ,TOTAL
 ,SUM(cast(PURCHASES as decimal(18,5)) )AS PURCHASES
 ,'' AS CCNAME
 ,'' AS CCTOTAL
 FROM   TableA


WHERE 

GROUP BY DESCRIPTION,STUDENTID,DOCDATE,VOUCHERDATE,DOCNUMB,PURCHASES

2 个答案:

答案 0 :(得分:2)

如果您想GROUP BY进行购买,则不应在SUM中加入购买。

同时将其从SELECT中删除。
然后,仅在SUMMAXAVG,...

等聚合函数中使用PURCHASES

此外,您可以删除该DISTINCT
因为GROUP BY应该已经足够返回唯一记录。

因此,请尝试以下操作:

SELECT 
 '1' AS DOCTYPE,
 DESCRIPTION, STUDENTID, DOCDATE, VOUCHERDATE, DOCNUMB,
 MAX(NAME) AS NAME,
 SUM(TOTAL) AS TOTAL,
 CAST(SUM(PURCHASES) AS DECIMAL(18,5)) AS PURCHASES,
 '' AS CCNAME,
 '' AS CCTOTAL
FROM TableA AS a
WHERE STUDENTID = 800130
GROUP BY DESCRIPTION, STUDENTID, DOCDATE, VOUCHERDATE, DOCNUMB

答案 1 :(得分:0)

如果任何列对于每个购买而言都是唯一的,并且会因购买行而异,请从查询中将其删除。

使用GROUP BY代替DISTINCT将使您对结果有更多的控制。

SELECT
    '1' AS DOCTYPE,
    DESCRIPTION,
    STUDENTID,
    DOCDATE,
    VOUCHERDATE,
    DOCNUMB,
    PURCHASES,
    NAME,
    TOTAL,
    SUM(cast(PURCHASES as decimal(18,5)) )AS PURCHASES,
    '' AS CCNAME,
    '' AS CCTOTAL
 FROM   TableA
 GROUP BY DESCRIPTION,
    STUDENTID,
    DOCDATE,
    VOUCHERDATE,
    DOCNUMB,
    NAME,
    TOTAL