即使使用GROUP BY CLAUSE也能显示所有结果

时间:2016-02-09 05:17:32

标签: sql ms-access vb6

查询: 如何按月分类?

select format(datee,'mmm-yyyy') as [Months],sum(amount) as Amount 
from ledger_broker 
where ref_from like 'Purchase' 
group by format(datee,'mmm-yyyy') 
order by format(datee,'mmm-yyyy') desc 

输出: enter image description here

2 个答案:

答案 0 :(得分:1)

尝试按您选择的同一列进行分组:

SELECT t.[Months], t.Amount
FROM
(
    SELECT MONTH(datee) AS theMonth, YEAR(datee) AS theYear,
        FORMAT(datee,'mmm-yyyy') AS [Months], SUM(amount) AS Amount
    FROM ledger_transporter
    WHERE ref_from LIKE 'Purchase'
    GROUP BY MONTH(datee), YEAR(datee), FORMAT(datee, 'mmm-yyyy')
) t
ORDER BY t.theYear DESC, t.theMonth DESC

按日期排序的一种方法是在查询中选择数字月份和年份。

答案 1 :(得分:0)

group by datee更改为group by format(datee,'mmm-yyyy')

select distinct format(datee,'mmm-yyyy') as [Months], sum(amount) as Amount
from ledger_transporter
where ref_from like 'Purchase'
group by format(datee,'mmm-yyyy')
order by Month(datee)

原因是我假设您的约会时间是01-FEB-2016和02-FEB-2016,但如果按照它分组,您将获得2个不同的记录。 但是,对于format(datee,'mmm-yyyy'),即FEB-2016,这两个日期都相同。因此不匹配