如何在DATEPART中使用GROUP?

时间:2014-06-27 06:05:52

标签: sql sql-server

我使用以下脚本来计算一年的ShopId数量。

我还需要按月将结果细分一年。

所以最终结果应该是

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
);

我的剧本应该改变什么?我应该在GROUP BY附近使用DATEPART

4 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

DatePart仅返回月份编号。如果您需要结果将有月名,那么您应该使用 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

答案 2 :(得分: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

答案 3 :(得分: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