带有group by子句的SQL datetime问题

时间:2017-03-19 17:13:22

标签: sql-server

以下是我的查询,它没有正确返回过去6个月的数据,因为我已经更改了我的日期时间格式。我想保持我的日期格式

select InventoryGroup,
    ProjectId,
    SubscriptionGuid,
    SUM(extendedcost) as Cost,
    RIGHT(CONVERT(varchar(10), [Date], 105), 7) as [YearMonth]
from CostDetails
group by InventoryGroup,
    ProjectId,
    SubscriptionGuid,
    RIGHT(CONVERT(varchar(10), [Date], 105), 7)
having InventoryGroup <> ''
    and (
        RIGHT(CONVERT(varchar(10), [Date], 105), 7) > RIGHT(CONVERT(varchar(10), DATEADD(MONTH, DATEDIFF(MONTH, 0, DATEADD(m, - 6, GETDATE())), 0), 105), 7)
        or RIGHT(CONVERT(varchar(10), [Date], 105), 7) = RIGHT(CONVERT(varchar(10), GETDATE() - 1, 105), 7)
        )

以下是我当前的输出

enter image description here

1 个答案:

答案 0 :(得分:1)

只是猜测整个问题是由使用having子句而不是where引起的。也许这会更好:

select InventoryGroup,
    ProjectId,
    SubscriptionGuid,
    SUM(extendedcost) as Cost,
    RIGHT(CONVERT(varchar(10), [Date], 105), 7) as [YearMonth]
from CostDetails
where InventoryGroup <> '' and 
    [Date] > DATEADD(MONTH, DATEDIFF(MONTH, 0, DATEADD(m, - 6, GETDATE())), 0)
group by InventoryGroup,
    ProjectId,
    SubscriptionGuid,
    RIGHT(CONVERT(varchar(10), [Date], 105), 7)

把它排除在外,因为以前的陈述总是如此(比过去6个月更新),如果它是昨天的那个月:

or RIGHT(CONVERT(varchar(10), [Date], 105), 7) = RIGHT(CONVERT(varchar(10), GETDATE() - 1, 105), 7)