如何按月按顺序获取结果集中的数据?

时间:2011-01-11 10:20:03

标签: sql-server-2005

下面工作正常,但我没有按月订单。你能告诉我什么想法吗?

SELECT SUM(TaxableAmt) [NSV], (UPPER(CONVERT(VARCHAR,LEFT(DATENAME(MM,invoicedate),3)))+'/'+ CONVERT(VARCHAR,RIGHT(DATENAME(YYYY,invoicedate),2))) AS MONTHYEAR  
FROM SALESDATA where (invoicedate >='4-1-2009' and invoicedate <='4-30-2010')
GROUP BY (UPPER(CONVERT(VARCHAR,LEFT(DATENAME(MM,invoicedate),3)))+'/'+ CONVERT(VARCHAR,RIGHT(DATENAME(YYYY,invoicedate),2)))

结果集是:

NSV                     MONTHYEAR  

45099947.4300001                  APR/09
83295380.4299992                  NOV/09
95838138.2              AUG/09
74326454.2599992        DEC/09
94144688.5400001        JUL/09
60688678.260001 MAR/10
58451739.9700001           APR/10
87555926.7200027          FEB/10
128036311.36            JAN/10
50949078.1699996        JUN/09
45232741.8099997        MAY/09
72846524.389999     OCT/09

1 个答案:

答案 0 :(得分:1)

您没有向SQL Server询问任何订单,可以按照自己喜欢的顺序自由返回数据。

这样做的一种方法(并将字符串操作减少到一个地方):

select NSV,UPPER(SUBSTRING(DATENAME(month,MonYear),1,3)) + '/' + RIGHT(DATEPART(year,MonYear),2)
from
(SELECT SUM(TaxableAmt) [NSV],DATEADD(month,DATEDIFF(month,'20010101',invoicedate),'20010101') as MonYear
FROM SALESDATA where (invoicedate >='20090401' and invoicedate <='20100430')
GROUP BY DATEADD(month,DATEDIFF(month,'20010101',invoicedate),'20010101')
) t
ORDER BY MonYear