2014-01-24 100 views
0

我設計了下面的SQL查詢來獲取這可能簡化這個SQL查詢嗎?

100 - ((reportedDate – Submission Date)/TotalNumOfVisits) * 100 

的百分比有什麼辦法來簡化呢?就像把這兩個查詢合併成一個?

SELECT 
    q1.VisitMonth,q1.TotalVisit, ISNULL(q2.diff,0) AS DIFF 
    ,100 - ISNULL((CAST((q2.diff * 1.0/q1.TotalVisit) * 100 AS FLOAT)),0) PERC 
FROM 
(
    SELECT DATENAME(MONTH,v.VisitDate) as VisitMonth, count(v.VisitID) as TotalVisit 
    FROM Visits v 
    INNER JOIN Assignments a ON a.AssignmentID = v.AssignmentID 
    WHERE a.ClientID IN (33,46) 
    AND v.VisitDate BETWEEN '01/01/2013' AND '31/12/2013' 
    group by DATENAME(MONTH,v.VisitDate) 
) q1 
LEFT OUTER JOIN 
(
    SELECT DATENAME(MONTH,v.VisitDate) as MonthName,COUNT(*) as diff 
    FROM Visits v 
    INNER JOIN Assignments a ON a.AssignmentID = v.AssignmentID 
    WHERE a.ClientID IN (33,46) 
    AND v.VisitDate BETWEEN '01/01/2013' AND '31/12/2013' 
    AND DATEDIFF(DAY,v.ReportDate,v.SubmissionDate) > 2 
    group by DATENAME(MONTH,v.VisitDate) 
) q2 
ON q1.VisitMonth = q2.MonthName 

結果:

enter image description here

+3

有針對我相信作品SQL,過C程序的規則:*任何C程序可減少到一行,然後包含至少一個錯誤*。 \ * scnr \ * –

回答

2

試試這個: -

Select 
     VisitMonth,isnull(diff,0) as DIFF, 
     100 - ISNULL((CAST((diff * 1.0/Nullif(TotalVisit,0)) * 100 AS FLOAT)),0) PERC 
from 
(
    SELECT 
     VisitMonth = Datename(month,visitDate) , 
     Diff = Sum(case when DATEDIFF(DAY,v.ReportDate,v.SubmissionDate) > 2 then 1 
        else 0 end) , 
     TotalVisit = Count(v.VisitID) 
FROM Visits v 
INNER JOIN Assignments a ON a.AssignmentID = v.AssignmentID 
WHERE a.ClientID IN (33,46) 
AND v.VisitDate BETWEEN '01/01/2013' AND '31/12/2013' 
group by DATENAME(MONTH,v.VisitDate) 
)a 
+0

@parveen:謝謝,它的效果很好。你知道,如果你的查詢和我設計的查詢有任何性能差異嗎? – user1263981

+0

對不起,我認爲你已經回答了我的問題。出於興趣,我已經對這兩個查詢運行了執行計劃,並且您的查詢計劃成本爲96%,我的查詢計劃成本爲54%。只是想知道爲什麼你的查詢在清晰和簡單的情況下花費了96%,並且在執行計劃中節點較少。對不起,沒有任何執行計劃的經驗。 – user1263981

+0

@ user1263981:'where'子句將在'Select query'中的計算列之前執行。在這種情況下,您的查詢將首先過濾數據,然後應用邏輯,作爲我的查詢將應用於每一行,並檢查'​​DATEDIFF(DAY,v.ReportDate,v.SubmissionDate)'是否大於2。請查看Itzik Ben-Gan的[文章](http://www.sql.co.il/books/insidetsql2008/Logical%20Query%20Processing%20Poster.pdf),它顯示了SQL Server處理的邏輯順序。順便說一下,不是每個簡單和可讀的查詢都是「高性能」的 – praveen