我有以下查询:
SELECT
DATEDIFF(day, DateUsed, DateExpires) AS DaysBetweenExpirationAndUse
FROM tblOffer
我怎样才能从DaysBetweenExpirationAndUse
列中获得平均天数?
我有以下查询:
SELECT
DATEDIFF(day, DateUsed, DateExpires) AS DaysBetweenExpirationAndUse
FROM tblOffer
我怎样才能从DaysBetweenExpirationAndUse
列中获得平均天数?
这应该可以正常工作:
SELECT AVG(DATEDIFF(d, DateUsed, DateExpires)) AS AvgDaysBetweenExpirationAndUse
FROM tbl
如果您想要 AVG 中的小数位:
SELECT AVG(DATEDIFF(d, DateUsed, DateExpires)*1.0) AS AvgDaysBetweenExpirationAndUse
FROM tbl
如果您也想选择AVG
和其他字段,而不分组:
SELECT *
,AVG(DATEDIFF(d, DateUsed, DateExpires)*1.0) OVER() AS AvgDaysBetweenExpirationAndUse
FROM tbl
这个sql可以执行吗?
SELECT AVG(t.a) from
(
SELECT DATEDIFF(d, DateUsed, DateExpires) AS a
FROM tbl
) as t
这是我的测试:
但好的答案是:
SELECT AVG(DATEDIFF(d, DateOne, DateTwo)*1.0) AS avgDate
FROM Test
SELECT AVG(DATEDIFF(d, DateUsed, DateExpires)) FROM tbl
应该可以正常工作。请注意,由于DATEDIFF
返回一个整数值,因此结果也将是一个整数。
如果您想要“精确”(就浮点数而言)平均值,请使用
SELECT AVG(CAST(DATEDIFF(d, DateUsed, DateExpires) AS FLOAT)) FORM tbl