在列列表中使用子查询

时间:2011-05-17 03:37:08

标签: sql tsql

我想创建一个查询,计算在过去7天,14天和28天内创建的记录数。我的结果将返回如下内容:

7Days  14Days  28Days  
21     35      56

我知道如何为每个timepsan例如7天,但是我在一个查询中捕获所有三个?

select count(*) from Mytable
where Created > DATEADD(day,-8, getdate()) 

4 个答案:

答案 0 :(得分:4)

也不漂亮,但不依赖于子查询(表/列名来自AdventureWorks)。如果case语句符合你的标准,则返回1,否则返回0 - 那么你只需对结果求和:

select sum(case when datediff(day, modifieddate, getdate()) <= 7
                then 1 else 0 end) as '7days',
       sum(case when datediff(day, modifieddate, getdate()) > 7
                     and datediff(day, modifieddate, getdate()) <= 14
                then 1 else 0 end) as '14days',
       sum(case when datediff(day, modifieddate, getdate()) > 14
                     and datediff(day, modifieddate, getdate()) <= 28
                then 1 else 0 end) as '28days'
from sales.salesorderdetail

编辑:更新了datediff函数 - 它的写入方式,它会返回一个负数(假设过去曾有过修改日期),导致所有项目都属于第一种情况。感谢Andriy M指出了

答案 1 :(得分:0)

它不是世界上最漂亮的代码,但它可以解决问题。尝试从三个子查询中进行选择,每个子查询对应一个范围。

select * from 
(select COUNT(*) as Cnt from    Log_UrlRewrites where CreateDate >= DATEADD(day, -7, getdate())) as Seven
inner join (select  COUNT(*) as Cnt from    Log_UrlRewrites where CreateDate >= DATEADD(day, -14, getdate())) as fourteen on 1 = 1
inner join (select  COUNT(*) as Cnt from    Log_UrlRewrites where CreateDate >= DATEADD(day, -28, getdate())) as twentyeight on 1 = 1

答案 2 :(得分:0)

select
(
  select count(*)
  from Mytable
  where Created > DATEADD(day,-8, getdate())
) as [7Days],
(
  select count(*)
  from Mytable
  where Created > DATEADD(day,-15, getdate())
) as [14Days], 
(
  select count(*)
  from Mytable
  where Created > DATEADD(day,-29, getdate())
) as [28Days] 

答案 3 :(得分:0)

SELECT
  [7Days]  = COUNT(CASE UtmostRange WHEN  7 THEN 1 END),
  [14Days] = COUNT(CASE UtmostRange WHEN 14 THEN 1 END),
  [28Days] = COUNT(CASE UtmostRange WHEN 28 THEN 1 END)
FROM (
  SELECT
    *,
    UtmostRange = CASE
      WHEN Created > DATEADD(day,  -8, GETDATE()) THEN  7
      WHEN Created > DATEADD(day, -15, GETDATE()) THEN 14
      WHEN Created > DATEADD(day, -29, GETDATE()) THEN 28
    END
  FROM Mytable
) s