2016-12-29 83 views
0

所以這就是我所在的位置(並且完全按照需要進行工作)。然而,這只是項目的第一步。因此,我們的目標是讓這個查詢的結果通過ODBC顯示在表單1上(從未這樣做,因此需要做大量的研究)。一旦顯示在excel用戶將能夠輸入日期範圍...讓我們說A1或B1(尚不確定在設計上)。所以這是我迄今爲止所擅長的。所以現在我正在尋找更多信息的第二張表單,然後失敗/成功。這第二張紙將完成第一張紙只顯示更多細節。這將只適用於失敗。加入兩個數量查詢

SELECT Sum(case when status = 6 then 1 else 0 end) as Failed, 
     Sum(case when status = 9 then 1 else 0 end) as Successful, 
    UniqueID 
Into #tempsheet1 
FROM Documents 
WHERE ownerID = 467 
and status in (6,9) 
and CreationTime between @StartDate and @EndDate 
Group By UniqueID 

Select D.UniqueID, FromName, ToName, CreationTime, 
cast(CreationTime as date) as CreationDate, cast(CreationTime as date) as CreationTime, 
ErrorCode, ElapsedSendTime, RemoteID 
From #tempsheet1 ts1 
Inner Join Documents D On 
D.UniqueID = ts1.UniqueID 
and [Status] = 9 

回答

1

你可以使用條件的聚集和總結VS個性化......

SELECT Sum(case when status = 6 then 1 else 0 end) as Failed, 
     Sum(case when status = 9 then 1 else 0 end) as Successful, 
     cast(CreationTime as date) CreationDate 
FROM Documents 
WHERE ownerID = 467 
    and status in (6,9) 
    and CreationDate between @StartDate and @EndDate 
GROUP BY cast(CreationTime as date) CreationDate 
ORDER BY cast(CreationTime as date) descending 

由於兩個查詢使用的文件表和相同的OWNERID過濾器,我們就可以篩選owerID的where子句。我在這個地方添加了6,9的狀態,因爲我們可以擁有很多我們不關心的狀態,爲什麼還要評估它們呢?

總和(case評估狀態,當6設置計數器爲1時,否則它將計數器設置爲0)這樣,所有1和0的總和將導致失敗或成功的「計數」。

+0

謝謝先生。不知道爲什麼這個工程雖然。 –

+0

其實這是產生不正確的結果。雖然設置是正確的。當我運行包含臨時表的原始代碼時,我得到的數字略有不同。 –

+0

總數與數量有差異。計數是正確的。 –

1
SELECT A.Failed,B.Successful --before it is '*' which means 'all columns' 
FROM 
(
SELECT COUNT([Status]) as Failed, 1 as JoiningValue 
    FROM Documents 
    Where ownerid = '467' 
    and [Status] = '6') as A 

INNER JOIN 

(
SELECT COUNT([Status]) as Successful, 1 as JoiningValue 
    FROM Documents 
    Where ownerid = '467' 
    and [Status] = '9') as B 

ON B.JoiningValue = A.JoiningValue 
+0

這幾乎是我想要的。我最終將設置一個ODBC來優化,所以我需要從select語句中刪除JoiningValue列(我知道它需要加入),但是我無法在顯示中使用它。 –

+0

查看我的更新回答:) – LONG

+0

這也適用。 –

0

就可以SELECT這兩個查詢,那麼你可以得到一個表中的值。

SELECT 
(SELECT COUNT([Status]) as Failed 
into #tempfailed 
FROM Documents 
Where ownerid = '467' 
and [Status] = '6') sa FAILED, 
(SELECT COUNT([Status]) as Successful 
FROM Documents 
Where ownerid = '467' 
and [Status] = '9') as Sucess