我正在学习SQL,并希望了解如何对计算字段进行计算(未存储在数据库中的值)。例如,我使用以下查询来获取客户支付发票所需的天数。这是发票上的过账日期(OINV.DocDate)与收款(ORCT.DocDate)上的过账日期之间的差异。
OINV =发票标题表 ORCT =收款表头 RCT2 =收款行表
SELECT OINV.cardcode, OINV.docnum, OINV.DocDate, ORCT.DocDate,
DATEDIFF(dd,OINV.DocDate,ORCT.DocDate) as DaystoPay
FROM OINV
INNER JOIN RCT2 ON OINV.DocNum = RCT2.DocEntry
INNER JOIN ORCT ON RCT2.DocNum = ORCT.docnum
ORDER BY OINV.cardcode
我的结果如下:
cardcode docnum DocDate DocDate DaystoPay
C20000 1 00:00.0 00:00.0 1296
C20000 75 00:00.0 00:00.0 1514
C20000 83 00:00.0 00:00.0 1478
C20000 91 00:00.0 00:00.0 1412
C23900 4 00:00.0 00:00.0 1271
C23900 37 00:00.0 00:00.0 1061
现在,我想按照客户对此进行分组,并计算客户支付发票的平均天数,即OINV.cardcode支付的发票,然后平均DaystoPay值。我怎样才能用SQL实现呢?
结果如下:
C20000 5700
C23900 2332
由于
答案 0 :(得分:2)
您的结果看起来像是想要总结DaystoPay而不是平均值。您可以使用聚合函数来执行此操作:
SELECT OINV.cardcode, SUM(DATEDIFF(dd,OINV.DocDate,ORCT.DocDate)) As DaystoPay
FROM OINV
INNER JOIN RCT2 ON OINV.DocNum = RCT2.DocEntry
INNER JOIN ORCT ON RCT2.DocNum = ORCT.docnum
GROUP BY OINV.cardcode
ORDER BY OINV.cardcode;
如果你想平均,那么你可能会将每张卡片的记录数除以DaystoPay的总数(我猜你的查询。)
看起来像这样:
SELECT OINV.cardcode,
SUM(DATEDIFF(dd,OINV.DocDate,ORCT.DocDate))/COUNT(OINV.cardcode) As AvgDaysToPay
FROM OINV
INNER JOIN RCT2 ON OINV.DocNum = RCT2.DocEntry
INNER JOIN ORCT ON RCT2.DocNum = ORCT.docnum
GROUP BY OINV.cardcode
ORDER BY OINV.cardcode;
或更简单:
SELECT OINV.cardcode,
AVG(DATEDIFF(dd,OINV.DocDate,ORCT.DocDate)) As AvgDaysToPay
FROM OINV
INNER JOIN RCT2 ON OINV.DocNum = RCT2.DocEntry
INNER JOIN ORCT ON RCT2.DocNum = ORCT.docnum
GROUP BY OINV.cardcode
ORDER BY OINV.cardcode;
这是一个有用的网站,用于了解有关聚合函数的更多信息:
http://www.w3schools.com/sql/sql_functions.asp (见下面的评论)
请务必注意,当您使用Group By子句时,必须在Group By列表中未包含的任何列上使用聚合函数。
希望这很有用!