【发布时间】:2013-04-04 23:22:56
【问题描述】:
我有一个表 Product 包含以下列
ProductId Name RegistrationDate UnregistrationDate
1 AB 2013-01-01 2013-03-01
2 CD 2013-01-10 2013-03-13
等
我想获得一份一年中每个月的注册产品列表。
示例:年、月以及已注册和未未注册的经销商数量。
Year Month RegisteredProucts
2013 2 35
2013 3 45(includes products even registered before March 2013)
我写了以下存储过程来查找一个月的注册产品: 并且有效:
@Begin Time = First Day of the Month
@End Time = Last Day of the Month
select COUNT(DISTINCT P.ProductId) as RegisteredProducts from Product P
where ((P.RegisteredDate < @EndTime)
AND (P.UnregisteredDate > @EndTime))
然后我编写了下面的查询,但它似乎按 RegisteredDate 对结果进行分组。 我想知道如何在每个月底之前对已注册的产品(不是未注册的)进行分组 为期一年?
select YEAR(P.RegisteredDate) AS [YEAR],MONTH(P.RegisteredDate) AS [MONTH], COUNT(DISTINCT P.ProductId) as RegisteredProducts from Product P
where ((P.RegisteredDate < @EndTime)
AND (P.UnregisteredDate > @EndTime))
group by YEAR(D.RegisteredDate), MONTH(D.RegisteredDate)
【问题讨论】:
标签: sql-server sql-server-2008 tsql sql-server-2008-r2