-1

我需要您按日期订购查询,然后如果可以简化它:-)

此查询将返回从当天开始每周的条目数。

这是查询:

SELECT CONVERT(VarChar(50), DATEADD(day, DATEDIFF(day, 0, GETDATE()), -7), 103) as periode_join, COUNT(u.usr_ID) as cptu 
FROM [USR_USER] u 
INNER JOIN [USI_USER_SITE] s ON u.USR_ID = s.USR_ID
WHERE u.[USR_JOINED_DT] >=  DATEADD(day, DATEDIFF(day, 0, GETDATE()), -7) and u.[USR_JOINED_DT] <=  DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0)

UNION

SELECT CONVERT(VarChar(50), DATEADD(day, DATEDIFF(day, 0, GETDATE()), -14), 103) as periode_join, COUNT(u.usr_ID) as cptu 
FROM [USR_USER] u 
INNER JOIN [USI_USER_SITE] s ON u.USR_ID = s.USR_ID
WHERE u.[USR_JOINED_DT] >=  DATEADD(day, DATEDIFF(day, 0, GETDATE()), -14) and u.[USR_JOINED_DT] <=  DATEADD(day, DATEDIFF(day, 0, GETDATE()), -7)   

UNION

SELECT CONVERT(VarChar(50), DATEADD(day, DATEDIFF(day, 0, GETDATE()), -21), 103) as periode_join, COUNT(u.usr_ID) as cptu 
FROM [USR_USER] u 
INNER JOIN [USI_USER_SITE] s ON u.USR_ID = s.USR_ID
WHERE u.[USR_JOINED_DT] >=  DATEADD(day, DATEDIFF(day, 0, GETDATE()), -21) and u.[USR_JOINED_DT] <=  DATEADD(day, DATEDIFF(day, 0, GETDATE()), -14)

UNION

SELECT CONVERT(VarChar(50), DATEADD(day, DATEDIFF(day, 0, GETDATE()), -28), 103) as periode_join, COUNT(u.usr_ID) as cptu 
FROM [USR_USER] u 
INNER JOIN [USI_USER_SITE] s ON u.USR_ID = s.USR_ID
WHERE u.[USR_JOINED_DT] >=  DATEADD(day, DATEDIFF(day, 0, GETDATE()), -28) and u.[USR_JOINED_DT] <=  DATEADD(day, DATEDIFF(day, 0, GETDATE()), -21)   

 UNION

SELECT CONVERT(VarChar(50), DATEADD(day, DATEDIFF(day, 0, GETDATE()), -35), 103) as periode_join, COUNT(u.usr_ID) as cptu  
FROM [USR_USER] u 
INNER JOIN [USI_USER_SITE] s ON u.USR_ID = s.USR_ID
WHERE u.[USR_JOINED_DT] >=  DATEADD(day, DATEDIFF(day, 0, GETDATE()), -35) and u.[USR_JOINED_DT] <=  DATEADD(day, DATEDIFF(day, 0, GETDATE()), -28)   

UNION

SELECT CONVERT(VarChar(50), DATEADD(day, DATEDIFF(day, 0, GETDATE()), -42), 103) as periode_join, COUNT(u.usr_ID) as cptu 
FROM [USR_USER] u 
INNER JOIN [USI_USER_SITE] s ON u.USR_ID = s.USR_ID
WHERE u.[USR_JOINED_DT] >=  DATEADD(day, DATEDIFF(day, 0, GETDATE()), -42) and u.[USR_JOINED_DT] <=  DATEADD(day, DATEDIFF(day, 0, GETDATE()), -35)
ORDER BY periode_join desc

这是结果:

periode_join    cptu
28/05/2013  8740
25/06/2013  9773
18/06/2013  8212
11/06/2013  6644
04/06/2013  9420
02/07/2013  7868

非常感谢:-D

4

1 回答 1

2

如果您有 SQL Server 2005 及更高版本,您可以尝试以下操作:

;with CTE_Data as
(
  select
        u.usr_id,
        cast(dateadd(dd, -(datediff(dd, u.usr_joined_dt, getdate()) / 7 + 1) * 7, getdate()) as date) as periode_join
    from usr_user as u 
        inner join usi_user_site as s on u.usr_id = s.usr_id
)
select periode_join, count(usr_id) as cptu
from CTE_Data
group by periode_join
order by periode_join asc

SQL 提琴示例

要按周拆分数据,我们必须从表中获取 getdate() 和日期之间的天数 - datediff(dd, u.usr_joined_dt, getdate()),然后我们必须得到整周数 - / 7,然后我们必须减去整周数 + 1。

因此,例如,如果日期 ='2013/06/30'那么天数 = 9,则整数周数 = 1,我们必须减去 1 + 1 周,所以我们得到'2013/06/25' 等等

于 2013-07-09T12:40:58.873 回答