2011-05-17 71 views
4

我想創建一個查詢,以計算在過去的7,14和28天內創建了多少條記錄。我的結果會返回類似於:在列列表中使用子查詢

7Days 14Days 28Days 
21  35  56 

我知道如何爲每個時間安排例如7天,但我可以在一個查詢中捕獲所有三個?

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

回答

4

而且不漂亮,但不依賴於子(表/列名來自AdventureWorks中)。如果它屬於你的標準內的情況下語句返回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函數 - 它是書面的方式,它會返回一個負數(假設修改日期過去)導致所有項目屬於第一種情況。感謝舍甫琴科M代表指出了這一點

+0

這是做到這一點的最有效方法。沒有理由編寫子查詢,而且速度非常慢。這個查詢對數據進行一次傳遞,非常快速和高效。 – Brettski 2011-05-17 04:16:30

+1

爲了獲得更好的性能,您應該在Created字段上創建索引,而不是'datediff(day,getdate(),Created)<= 7',使用'Created <= datediff(day,-7,getdate())'強制索引查找。 – Dalex 2011-05-17 06:20:04

+0

'modifieddate'應該早於還是晚於'GETDATE()'? – 2011-05-17 12:24:11

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 
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] 
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