2014-06-27 97 views
0

我正在使用以下腳本來計算一年的ShopId數量。如何使用GROUP with DATEPART?

我還需要將結果按月分解一年。

所以,最終的結果應該是

MONTH 1 
    SHOPID 5  100 
    SHOPID 4  90 
MONTH 2 
    SHOPID 1  150 
    SHOPID 4  80 

SELECT ShopId, Count(ShopId) as Interest 
    FROM dbo.Analytics 
    WHERE DateCreated >= '2014' AND DateCreated < '2015' 
    GROUP BY ShopId ORDER BY Interest DESC 

表結構

CREATE TABLE Analytics 
(
DateCreated dateTime2(2), 
ShopId int 
); 

我應該在我的腳本改變什麼?我將使用DATEPART附近GROUP BY

+0

任何建議更好的標題是w elcome :-) – GibboK

+0

DateCreated是DateTime字段? – Jesuraja

+1

請同時發佈您的表格結構 – Raj

回答

1

您可以使用DatePart

嘗試這樣

SELECT DatePart(mm,datecreated) 'Month',ShopId, Count(ShopId) as Interest 
    FROM dbo.Analytics 
    WHERE year(DateCreated) = '2015' 
    GROUP BY Datepart(mm,datecreated),ShopId 
    ORDER BY Interest DESC 

日期部分將只返回月份數。如果你需要的結果將具有月份名稱,那麼你應該使用DATENAME

試試這個

SELECT Select DateName(month , DateAdd(month , DatePart(mm,datecreated) , -1)) 'Month',ShopId, Count(ShopId) as Interest 
    FROM dbo.Analytics 
    WHERE year(DateCreated) = '2015' 
    GROUP BY DateName(month , DateAdd(month , DatePart(mm,datecreated) , -1)),ShopId 
    ORDER BY Interest DESC 
+0

您如何按月訂購? – GibboK

+1

@GibboK只需使用'Order By DatePart(mm,datecreated)' –

1

試試這個

SELECT datepart(mm,datecreated) 'Month',ShopId, Count(ShopId) as Interest 
    FROM dbo.Analytics 
    WHERE year(DateCreated) = '2014' 
    GROUP BY datepart(mm,datecreated),ShopId ORDER BY Interest DESC 
0

試試這個:

SELECT  DATEPART(MONTH, DateCreated) AS MONTH, ShopId, COUNT(ShopId) AS Interest 
FROM  dbo.Analytics 
WHERE  YEAR(DateCreated) = '2014' 
GROUP BY DATEPART(MONTH, DateCreated), ShopId 
ORDER BY DATEPART(MONTH, DateCreated) ASC, Interest DESC 
0

在這裏,你會需要組年過櫃面有是更廣泛的時間範圍:

select convert(varchar(6), DateCreated, 112) as Time, shopid, Count(ShopId) as Interest 
    FROM Analytics 
    WHERE DateCreated >= '2014' AND DateCreated < '2015' 
    GROUP BY convert(varchar(6), DateCreated, 112), ShopId ORDER BY Interest DESC