2015-02-10 174 views
0

我有一个SQL查询,其中我检索一些数据使用JOINS也有DateTime字段Delivery,但虽然检索我将它转换为字符串的格式MMM YYYY但在最后我想按Delivery对整个列表进行排序,但是当我将该列转换为字符串时,我不确定如何按原始DateTime字段Delivery排序结果。我的查询如下按日期类型字符串排序在SQL Server 2012中

WITH deliveryProducts AS 
(
    SELECT DISTINCT FORMAT(a.Delivery,'MMMM yyyy') AS Delivery, b.Product 
    FROM DEALS as a, PRODUCTS as b Where a.TradeDate<[email protected] 
) 
, deliveryActuals AS 
(
    SELECT 
      FORMAT(a.Delivery,'MMMM yyyy') AS Delivery, 

      b.Product,COUNT(a.Id) AS Trades, 
      ((6.2898*SUM(a.Volume))/DAY(EOMONTH(DATEADD(MONTH, DATEDIFF(MONTH, 0,a.Delivery), 0))))*0.001 AS BBLperDay, 
      SUM(a.Volume) AS M3, 

     SUM(a.Volume*a.Price)/Sum(a.Volume) AS WeightedAverage 
FROM  Deals AS a right outer join Products AS b 
      ON a.Product=b.Product AND 
      a.TradeDate<[email protected] 
GROUP BY b.Product, 

      DATEADD(MONTH, DATEDIFF(MONTH, 0,a.Delivery),0), FORMAT(a.Delivery,'MMMM yyyy') 

) 

SELECT 
    dp.Delivery, dp.Product, trades, BBLperDay, M3, WeightedAverage 
FROM 
    deliveryProducts dp 

    LEFT JOIN deliveryActuals da 
    on dp.Delivery = da.Delivery 
    and dp.product = da.Product 

ORDER BY dp.Delivery,dp.Product 

上述查询给我所需要的数据,但通过种种作为Delivery一个string

我可以知道一个更好的方法来解决这个问题吗?

回答

1
ORDER BY cast(dp.Delivery as date), dp.Product 

SQL Server可以处理铸造字符串“MMMM YYYY”或“MMM YYYY”来日期或日期时间。

+0

工作很好。谢谢 – DoIt 2015-02-10 14:19:38

0

您可以通过月份和年份为整数组,然后格式化在结束日期:

WITH deliveryProducts AS 
(
    SELECT MONTH(a.Delivery) AS DeliveryMonth, 
      YEAR(a.Delivery) AS DeliveryYear, 
      b.Product 
    FROM DEALS as a, PRODUCTS as b 
    WHERE a.TradeDate <= @tradeEndDate 
) 
, deliveryActuals AS 
(
    SELECT MONTH(a.Delivery) AS DeliveryMonth, 
      YEAR(a.Delivery) AS DeliveryYear, 
      b.Product,COUNT(a.Id) AS Trades, 
      ((6.2898*SUM(a.Volume))/DAY(EOMONTH(DATEADD(MONTH, DATEDIFF(MONTH, 0,a.Delivery), 0))))*0.001 AS BBLperDay, 
      SUM(a.Volume) AS M3, 

     SUM(a.Volume*a.Price)/Sum(a.Volume) AS WeightedAverage 
FROM  Deals AS a right outer join Products AS b 
      ON a.Product=b.Product AND 
      a.TradeDate<[email protected] 
GROUP BY b.Product, 
      MONTH(a.Delivery), 
      YEAR(a.Delivery) 

) 

SELECT 
    FORMAT(
     CAST(CAST(dp.DeliveryYear AS VARCHAR(4)) + 
    RIGHT('0' + CAST(dp.DeliveryMonth AS VARCHAR(2)), 2) + 
    RIGHT('0' + CAST(1 AS VARCHAR(2)), 2) 
AS DATETIME), 'MMMM yyyy'), 
    dp.Product, trades, BBLperDay, M3, WeightedAverage 
FROM 
    deliveryProducts dp 

    LEFT JOIN deliveryActuals da 
    on dp.DeliveryMonth = da.DeliveryMonth 
    and dp.DeliveryYear = da.DeliveryYear 
    and dp.product = da.Product 

ORDER BY dp.DeliveryYear, dp.DeliveryYear, dp.Product