如何在联合查询中对月份名称进行排序

时间:2014-12-23 02:50:33

标签: sql sorting

我有两个问题。查询1按月名称显示表。按工作周查询两个显示表。我联合了两个表,但问题是表1显示的月份名称顺序不正确。

我想这样显示:

October    
November    
WW52


SELECT Month, InputQuantity, ShippingQuantity FROM
(
   SELECT DATENAME(MONTH, dbo.SBR.SBR_DateCreated) AS Month, 
   SUM(dbo.SBR.SBR_Quantity) AS InputQuantity, 
   SUM(dbo.SBR.SBR_ShippingQuantity) AS ShippingQuantity 
   FROM dbo.SBR WHERE DATENAME(MONTH, SBR_DateCreated) <> DATENAME(MONTH, GETDATE()) 
   GROUP BY DATENAME(MONTH, dbo.SBR.SBR_DateCreated)
UNION
   SELECT dbo.SBR.SBR_WorkingWeek AS Month, 
   SUM(dbo.SBR.SBR_Quantity) AS InputQuantity, 
   SUM(dbo.SBR.SBR_ShippingQuantity) AS ShippingQuantity
   FROM dbo.SBR
  INNER JOIN dbo.WorkingWeek 
    ON dbo.SBR.SBR_WorkingWeek=dbo.WorkingWeek.WorkingWeek
  WHERE (dbo.WorkingWeek.DateFrom < GETDATE() 
  AND dbo.WorkingWeek.DateTo > GETDATE())
  GROUP BY dbo.SBR.SBR_WorkingWeek
) AS UWAIS

And Current OUTPUT:

Month       InputQuantity   ShippingQuantity    
November         12                12    
October          12                12    
WW52             13                10

2 个答案:

答案 0 :(得分:0)

ORDER BY SBR_DateCreated放在第一个子查询中。

SELECT Month, InputQuantity, ShippingQuantity FROM
(
SELECT DATENAME(MONTH, dbo.SBR.SBR_DateCreated) AS Month, SUM(dbo.SBR.SBR_Quantity) AS InputQuantity, SUM(dbo.SBR.SBR_ShippingQuantity) AS ShippingQuantity FROM dbo.SBR WHERE DATENAME(MONTH, SBR_DateCreated) <> DATENAME(MONTH, GETDATE()) 
GROUP BY DATENAME(MONTH, dbo.SBR.SBR_DateCreated)
ORDER BY dbo.SBR.SBR_DateCreated
UNION
SELECT dbo.SBR.SBR_WorkingWeek AS Month, SUM(dbo.SBR.SBR_Quantity) AS InputQuantity, SUM(dbo.SBR.SBR_ShippingQuantity) AS ShippingQuantity
FROM dbo.SBR
INNER JOIN dbo.WorkingWeek ON dbo.SBR.SBR_WorkingWeek=dbo.WorkingWeek.WorkingWeek
WHERE (dbo.WorkingWeek.DateFrom < GETDATE() AND dbo.WorkingWeek.DateTo > GETDATE())
GROUP BY dbo.SBR.SBR_WorkingWeek

) AS UWAIS

答案 1 :(得分:0)

我会在每个子查询中添加一个额外的列来表示该月份中的一个日期。然后可以将其用于order by

SELECT Month, InputQuantity, ShippingQuantity
FROM (SELECT DATENAME(MONTH, s.SBR_DateCreated) AS Month,
             SUM(s.SBR_Quantity) AS InputQuantity, SUM(s.SBR_ShippingQuantity) AS ShippingQuantity,
             MIN(s.SBR_DateCreated) as mindc
      FROM dbo.SBR s
      WHERE DATENAME(MONTH, SBR_DateCreated) <> DATENAME(MONTH, GETDATE()) 
      GROUP BY DATENAME(MONTH,s.SBR_DateCreated)
      UNION ALL
      SELECT s.SBR_WorkingWeek AS Month, SUM(s.SBR_Quantity) AS InputQuantity,
             SUM(s.SBR_ShippingQuantity) AS ShippingQuantity,
             MIN(ww.<datecol>)
      FROM dbo.SBR s INNER JOIN
           dbo.WorkingWeek ww
           ON s.SBR_WorkingWeek = ww.WorkingWeek
      WHERE (ww.DateFrom < GETDATE() AND ww.DateTo > GETDATE())
      GROUP BY s.SBR_WorkingWeek
     ) UWAIS
ORDER BY mindc;

不幸的是,我不知道哪个列用于第二个子查询。但其中一个表格中可能有适当的日期。

另外:

  • 我将union更改为union all。没有理由承担删除重复项的开销。
  • 我添加了可用的别名,因此查询更容易阅读。