2009-11-28 59 views
1

我想了解兩個日期的差異以及發生差異的頻率。我可以使用:SQL Server - 不能在DATEDIFF上做COUNT而不做CREATE VIEW

SELECT 
    DATEDIFF (day, db1.dbo.t1.Date1, db2.dbo.t2.Date2) AS Days 
FROM 
    db1.dbo.t1 
JOIN 
    db2.dbo.t2 ON db1.dbo.t1.wID = db2.dbo.t2.cID 
       AND db1.dbo.t1.Action LIKE 'Standard' 
       AND db2.dbo.t2.Status = 'CLOSED' 

,它將返回:

Days 
----- 
4 
4 
8 
21 
16 
42 
... 

現在我想要得到的那些天數,像這樣:

Days Diff 
----- ----- 
0  100 
1  40 
2  22 
3  25 
... 

我沒有權限在分貝創建視圖,所以我在想一個嵌套語句,如:

SELECT 
    Days, COUNT (*) AS Diff 
FROM 
    Days 
WHERE EXISTS 
(
SELECT DATEDIFF (day, db1.dbo.t1.Date1, db2.dbo.t2.Date2) AS Days 
FROM db1.dbo.t1 JOIN db2.dbo.t2 
ON db1.dbo.t1.wID = db2.dbo.t2.cID 
AND db1.dbo.t1.Action LIKE 'Standard' 
AND db2.dbo.t2.Status = 'CLOSED' 
) 
GROUP BY Days 

但我不斷收到錯誤消息207和208!

請告訴我我做錯了什麼。我一直在尋找和嘗試各種各樣的東西,但迄今爲止我所能想到的都是某種程度上我需要給'db1.dbo.t1 JOIN db2.dbo.t2'一個別名,所以我可以這樣稱呼它:

SELECT Days, COUNT (*) AS Diff 
FROM new_dual_db_alias 
WHERE EXISTS 

感謝,

回答

1

我認爲 - 儘管我不是在一個位置,快速測試:

SELECT Days, COUNT(Days) FROM 
(
SELECT 
    DATEDIFF (day, db1.dbo.t1.Date1, db2.dbo.t2.Date2) AS Days 
FROM 
    db1.dbo.t1 JOIN db2.dbo.t2 ON db1.dbo.t1.wID = db2.dbo.t2.cID AND 
            db1.dbo.t1.Action LIKE 'Standard' AND 
            db2.dbo.t2.Status = 'CLOSED' 
) 
GROUP BY Days 
1

在SQL Server 2005和了,你也可以使用一個CTE(公共錶快遞)

WITH DateDiffDays AS 
(
    SELECT 
    DATEDIFF (day, db1.dbo.t1.Date1, db2.dbo.t2.Date2) AS Days 
    FROM 
    db1.dbo.t1 
    JOIN 
    db2.dbo.t2 ON db1.dbo.t1.wID = db2.dbo.t2.cID 
    WHERE 
    db1.dbo.t1.Action LIKE 'Standard' 
    AND db2.dbo.t2.Status = 'CLOSED' 
) 
SELECT Days, COUNT(*) 
FROM DateDiffDays 
GROUP BY Days 
ORDER BY COUNT(*) 

一個CTE就像是一個「即時查看」,它對於下一個語句是有效的。

這是否適合您?