2013-12-17 19 views
0

我需要一些幫助來完成此查詢。這是我到目前爲止:在SQL中只顯示需要的結果

select 
    (select count(fileName) 
    from PDFFile 
    where dateTime > cast(getdate() as date) 
    and stateId = 17) AS "Files on SFTP" 
    , 
    (select count(fileName) 
    from PDFFile 
    where dateTime > cast(getdate() as date) 
    and stateId = 12) AS "Files Pass" 
    , 
    ((select count(fileName) 
    from PDFFile 
    where dateTime > cast(getdate() as date) 
    and stateId = 17) 
    - 
    (select count(fileName) 
    from PDFFile 
    where dateTime > cast(getdate() as date) 
    and stateId = 12)) AS "Diff" 

這會給我3列結果。第一個結果將是一個數字,第二個將是一個數字,第三個將是差異。甚至可能有更好的方法來寫這個,但我仍然是一個新手。提示:對於每一個國家在DB的條目:拉動

fileName |dateTime     | stateID 
--------+---------+-----------------+--------- 
abc.pdf | 2013-12-17 12:03:14.597 | 17 
abc.pdf | 2013-12-17 12:06:23.096 | 12 
xyz.pdf | 2013-12-17 12:09:16.583 | 17 
xyz.pdf | 2013-12-17 12:10:19.823 | 12 

不管怎麼說爲壓軸...

我需要有一個4列或一個單獨的查詢(可能UNION?) fileNames基於diff中的結果。

假設diff是40,第4列或單獨查詢應列出40個名稱。有時差異可能是負面的,所以假設在-40的時候應該列出40個名字。

非常感謝幫助。謝謝!

+0

你想要輸出的內容不清楚。您可以根據您發佈的樣本數據添加預期的輸出嗎? (「基於這個樣本數據,我想要得到這個輸出:」) –

回答

1

可以使用條件聚集大大簡化查詢:

select sum(case when dateTime > cast(getdate() as date) and stateId = 17 then 1 else 0 
      end) as "Files on SFTP", 
     sum(case when dateTime > cast(getdate() as date) and stateId = 12 then 1 else 0 
      end) AS "Files Pass", 
     (sum(case when dateTime > cast(getdate() as date) and stateId = 17 then 1 else 0 
      end) - 
     sum(case when dateTime > cast(getdate() as date) and stateId = 12 then 1 else 0 
      end) 
     ) as diff 
from PDFFile; 

若要取得第一組中,但不是第二個需要多一點的邏輯文件的列表。問題是聚合單位在文件級別。

select PDFFile 
from PDFFile 
group by PDFFile 
having sum(case when dateTime > cast(getdate() as date) and stateId = 17 then 1 else 0 
      end) > 0 and 
     sum(case when dateTime > cast(getdate() as date) and stateId = 12 then 1 else 0 
      end) = 0; 

having子句的每個部分都計算匹配兩個條件的行數 - 對於每個文件。您至少需要一行匹配第一個條件(因此爲> 0)且沒有匹配第二個(= 0)的行。

1

這種類型的「將行數據合併成一列」的問題在Stack Overflow上出現了很多,儘管它有它的地方,但以另一種方式解決問題通常更容易和更高效。

例如,要求SQL「給我所有的文件名,其中stateid = 17」很容易,將它們返回給您的應用程序,然後讓應用程序顯示它們。也可能是用戶不希望看到他們,直到他們需要進一步深入研究他們感興趣的特定摘要行。以電子郵件爲例 - 您只需要查看30個字符的主題行,並知道您無需下載1Mb電子郵件正文。

對於你的第一個問題,雖然有更容易(和更有效率)的方式來編寫你的查詢。注意,這個例子是未經測試

select 
    sum(case when stateId = 17 then 1 else 0 end) as "Files on SFTP", 
    sum(case when stateId = 12 then 1 else 0 end) as "Files Pass", 
    sum(case when stateId = 17 then 1 else 0 end) - 
      sum(case when stateId = 12 then 1 else 0 end) as "Diff", 
from 
    PdfFile 
where 
    datetime > getdate() 

我使用CASE這裏,防止發生要做到三個獨立的子查詢。子查詢效率低下。 CASE不是很好,但它比子查詢更快。我還將日期時間檢查作爲WHERE放在查詢的底部,因爲它對每個檢查都很常見。

+0

和@Gordon Linoff你的答案都可以用來壓縮子查詢。現在我只需要列出差異。在Excel中或多或少的VLOOKUP。在第二部分嘗試戈登的建議 –