2015-06-14 130 views
4

我試圖獲得一天內銷售數量的總和。我需要結果在ORDER BY日期。下面的查詢給我我需要的確切結果,除了日期沒有格式化爲我所需要的。Group By Date和SUM int - 日期格式和訂單

SELECT CAST(Datetime AS DATE) AS 'date', SUM(quantity) as total_quantity 
FROM Invoice_Itemized ii 
INNER JOIN Invoice_Totals it ON it.Invoice_Number = ii.Invoice_Number 
WHERE ii.ItemNum = '4011' 
AND it.datetime > '05/15/2015' 
GROUP BY CAST(Datetime AS DATE) 

SELECT DATENAME(MM, datetime) + ' ' + CAST(DAY(datetime) AS VARCHAR(2)) AS [DD Month], SUM(quantity) as total_quantity 
FROM Invoice_Itemized ii 
INNER JOIN Invoice_Totals it ON it.Invoice_Number = ii.Invoice_Number 
WHERE ii.ItemNum = '4011' 
AND it.datetime > '05/15/2015' 
GROUP BY DATENAME(MM, datetime) + ' ' + CAST(DAY(datetime) AS VARCHAR(2)) 

結果頂端查詢:

  1. 2015年5月15日91.43
  2. 2015年5月16日84.77

結果底部查詢:

  1. 6月1日128.34
  2. 6月10日85.06

頂部查詢爲我提供了我需要的信息,以我需要的順序。 底部查詢爲我提供了我需要的日期格式,但順序錯誤。

回答

3

如果你真的需要應用不同的格式,你可以使用派生表做到這一點:

select 
    DATENAME(MM, [date]) + ' ' + CAST(DAY([date]) AS VARCHAR(2)) AS [DD Month], 
    total_quantity 
from 
(
    SELECT CAST([Datetime] AS DATE) AS [date], SUM(quantity) as total_quantity 
    FROM Invoice_Itemized ii 
    INNER JOIN Invoice_Totals it ON it.Invoice_Number = ii.Invoice_Number 
    WHERE ii.ItemNum = '4011' 
    AND it.[datetime] > '05/15/2015' 
    GROUP BY CAST(Datetime AS DATE) 
) as X 

這樣你就可以換到成果轉化爲派生表,然後在適用的操作的其餘部分。

我會以爲這會工作過,但現在還不能測試:

SELECT DATENAME(MM, CAST([datetime] AS DATE)) + ' ' 
+ CAST(DAY(CAST([datetime] AS DATE)) AS VARCHAR(2)) AS [DD Month], 
SUM(quantity) as total_quantity 
FROM Invoice_Itemized ii 
INNER JOIN Invoice_Totals it ON it.Invoice_Number = ii.Invoice_Number 
WHERE ii.ItemNum = '4011' 
AND it.[datetime] > '05/15/2015' 
GROUP BY CAST([datetime] AS DATE) 
+0

我測試你的第二個查詢。正如我所需要的那樣工作。謝謝! – user3556177