如果是月份名称,如何以升序排序结果

时间:2016-03-17 10:13:41

标签: sql sql-server

我正在编写一个查询来汇总来自两个不同表格的值,并查找每月的销售和购买情况。在那之后,我按升序排序,正如预期的那样,它给出了错误的结果,即8月即将到来。

如何修改查询以正确获取结果?

这是我的问题:

 SELECT COALESCE(o.Month , p.Month) Month,
        ISNULL([Sale Cost],0) [Sale Cost],
        ISNULL([Purchase Cost],0) [Purchase Cost]
 FROM (
     Select sum(S.Cost) AS [Purchase Cost],
            DateName( month , DateAdd( month , month(S.[Date_Added]) , -1 ) ) As Month
     from dbo.Spare_Inventory AS S
     where YEAR(GETDATE()) = YEAR(S.[Date_Added])
     GROUP BY month(S.[Date_Added])
     ) o
 FULL JOIN (
     Select sum(B.[Total Price]) AS [Sale Cost],
            DateName(month, DateAdd( month , month(B.[DateOfSale]) , -1 ) ) As Month
     from dbo.Spare_Sale_DB AS B
     where YEAR(GETDATE()) = YEAR(B.[DateOfSale])
     GROUP BY month(B.[DateOfSale])) p
 ON o.Month = p.Month
 ORDER BY Month Asc

1 个答案:

答案 0 :(得分:2)

你有点自己给出答案;你希望你的行按月号而不是月份名称。所以只按月份编号。

SELECT 
  COALESCE(o.Month , p.Month) Month,
  ISNULL([Sale Cost],0) [Sale Cost] , 
  ISNULL([Purchase Cost],0)[Purchase Cost]
 FROM 
(
  Select 
    sum(S.Cost) AS [Purchase Cost], 
    DateAdd( month , month(S.[Date_Added]) , -1 ) As MonthNo,
    DateName( month , DateAdd( month , month(S.[Date_Added]) , -1 ) ) As Month 
  from dbo.Spare_Inventory AS S 
  where YEAR(GETDATE())=YEAR(S.[Date_Added]) 
  GROUP BY month(S.[Date_Added]) 
) o
FULL JOIN 
(
  Select 
    sum(B.[Total Price]) AS [Sale Cost], 
    DateName( month , DateAdd( month , month(B.[DateOfSale]) , -1 ) ) As Month 
  from dbo.Spare_Sale_DB AS B 
  where YEAR(GETDATE())=YEAR(B.[DateOfSale]) GROUP BY month(B.[DateOfSale])
) p ON o.Month = p.Month
ORDER BY o.MonthNo Asc;