我有一个查询,该查询应该仅从所有现有记录中获取当月最后一天的值(所以是多个月的最后一天)。由于使用了SUM()子句,因此无法仅获得最后一天需要的值。这是将整个月的所有值加在一起。我能以另一种方式只获得最后一天的价值吗?有什么我想念的吗?
到目前为止的代码:
SELECT
ID,
[Customer Name],
Year([ValDate]) & IIf(Len(Month([ValDate]))>1,Month([ValDate]),"0" & Month([ValDate])) AS BalMonth,
Sum(Value) AS LastValue
FROM
Archive
GROUP BY
ID,
[Customer Name],
Year([ValDate]),
Month([ValDate])
ORDER BY
ID,
Year(ValDate) & Month(ValDate)
已测试其他代码:
SELECT
ID,
[Customer Name],
YEAR([ValDate]) & MONTH([ValDate]) & MAX(DAY([BalDate])) AS LastDayofMonth
FROM
Archive
GROUP BY
ID ,
[Customer Name],
YEAR([ValDate]),
MONTH([ValDate])
ORDER BY
ID,
[Customer Name],
YEAR([ValDate]),
MONTH([ValDate])
第二部分代码无效,因为它以YYYYMMDD
格式生成日期。这使得它不允许对日期进行正确的排序。而是按1,10,11,12,2,3,4等顺序排列日期。
如果有任何不清楚的地方,我会尽力澄清,让我知道!
答案 0 :(得分:2)
尝试类似的东西:
SELECT
ID,
[Customer Name],
[ValDate] AS LastDayofMonth,
Sum([FieldToSum]) As Total
FROM
Archive
GROUP BY
ID,
[Customer Name],
[ValDate]
HAVING
[ValDate] = DateSerial(Year([ValDate]), Month([ValDate]) + 1, 0)
编辑:
要以格式日期输出,请尝试以下操作:
SELECT
ID,
[Customer Name],
Format([ValDate], "yyyymmdd") AS LastDayofMonth,
Sum([FieldToSum]) As Total
FROM
Archive
WHERE
[ValDate] = DateSerial(Year([ValDate]), Month([ValDate]) + 1, 0)
GROUP BY
ID,
[Customer Name],
Format([ValDate], "yyyymmdd")