如何按升序排序日期?

时间:2016-11-16 09:47:59

标签: sql sql-server sql-server-2008 tsql

我已经编写了这段代码并且有效。它显示了按月份分组的总金额等,但我希望以升序显示月份,年份,但它会随机排序显示,即2016年6月,2016年5月等。

SELECT DATENAME(MONTH, pd.PaymentDate) + ' ' + DATENAME(YEAR, pd.PaymentDate) AS PDate,
                   SUM(Case when PT.PropertyTypeName = 'Commercial' then PD.PropertyDetailsTotalAmount else 0 END) as CommercialIncome, 
                   SUM(Case when PT.PropertyTypeName = 'Residential' then PD.PropertyDetailsTotalAmount else 0 END) as ResidentialIncome,
                   COUNT(Case when PT.PropertyTypeName = 'Commercial' then PD.pk_PropertyDetails_PropertyDetailsID else NULL END) as TotalCommercialMaps,
                   COUNT(Case when PT.PropertyTypeName = 'Residential' then PD.pk_PropertyDetails_PropertyDetailsID else NULL END) as TotalResidentialMaps,

                   (Count(Case when PT.PropertyTypeName = 'Commercial' then PD.pk_PropertyDetails_PropertyDetailsID else NULL END)
                   +
                   COUNT(Case when PT.PropertyTypeName = 'Residential' then PD.pk_PropertyDetails_PropertyDetailsID else NULL END)) TotalMaps,

                   (SUM(Case when PT.PropertyTypeName = 'Commercial' then PD.PropertyDetailsTotalAmount else 0 END)
                   +
                   SUM(Case when PT.PropertyTypeName = 'Residential' then PD.PropertyDetailsTotalAmount else 0 END)) as TotalIncome

            From PropertyDetails PD
            Inner Join Properties P
            ON PD.fk_Properties_ID= p.pk_Properties_ID
            Inner Join PropertyTypes PT
            ON PT.pk_PropertyTypes_PropertyTypeID= P.fk_PropertyTypes_ID
            where
            PD.Paid= 1 
            and PaymentDate >= @DateFrom AND PaymentDate < DATEADD(day,1,@DateTo)
            Group By DATENAME(MONTH, pd.PaymentDate) + ' ' + DATENAME(YEAR, pd.PaymentDate)

3 个答案:

答案 0 :(得分:1)

您需要将组更改为

Group By DATENAME(MONTH, pd.PaymentDate) + ' ' + DATENAME(YEAR, pd.PaymentDate), DatePART(Month, pd.PaymentDate), DatePart(YEAR, pd.PaymentDate)
order by DatePart(YEAR, pd.PaymentDate) asc, DatePART(Month, pd.PaymentDate) asc

或类似。

答案 1 :(得分:0)

group by DATENAME(MONTH,pd.PaymentDate) ,DATENAME(YEAR,pd.PaymentDate),MONTH(pd.PaymentDate),YEAR(pd.PaymentDate)
order by YEAR(pd.PaymentDate) asc,MONTH(pd.PaymentDate) asc

答案 2 :(得分:-1)

简单如

....
group by DATENAME(MONTH,pd.PaymentDate) , DATENAME(YEAR,pd.PaymentDate),MONTH(pd.PaymentDate), YEAR(pd.PaymentDate)
order by YEAR(pd.PaymentDate) desc, MONTH(pd.PaymentDate) desc