2013-05-16 44 views
0

我需要一個查詢,以從下表中檢索值SQL查詢到不同條件下的兩排比較

enter image description here

我需要一個查詢計數的項目,其總和(總天數)總數位置1大於總和(totaldays)在位置2

請幫我

+0

是什麼你想要的輸出?爲什麼?有沒有隻有兩個值的位置? –

+0

這聽起來像家庭工作......請說明你需要數數? –

+0

請詳細說明您的問題,請輸入您需要的輸出內容。 –

回答

2
Select Count(T1.ProjectId) from (Select ProjectId ,Sum(TotalDay) as TL1 from Project where Location=1 gROUP BY ProjectId) t1 
inner Join 
(Select ProjectId ,Sum(TotalDay) as Tl2 from Project where Location=2 grOUP BY ProjectId) t2 
on 
t1.ProjectId=T2.ProjectId AND t1.tl1>t2.tl2 

Sql Fiddle Demo

2

試試這個:

DECLARE @a TABLE (
    projectid INT, 
    totalday INT, 
    location INT 
) 

INSERT @a (projectid, totalday, location) 
VALUES 
    (12,   20,  2), 
    (12,   10,  1), 
    (13,   2,   1) 

;WITH CTE AS (
    SELECT projectid, SUM(totalday) AS totalday, location FROM @a GROUP BY projectid, location 
) 
SELECT COUNT(*) 
FROM CTE AS a1 
INNER JOIN CTE AS a2 
    ON a1.projectid = a2.projectid 
WHERE 
    a1.location = 1 AND a2.location = 2 
    AND a1.totalday > a2.totalday 
+0

親愛的安德烈,謝謝..但這裏表中包含很多值..我剛剛編輯了像總天數之和的問題... – suhail

+0

然後使用StuardLC的答案 - 它看起來不錯 –

+0

反正我編輯了我的帖子 –

2

假設您的數據沒有唯一的密鑰約束,我首先用CTE總結每個項目每個位置的總天數 - 如果您的數據是唯一的,那麼您可以跳過此步驟。

WITH ProjectDays AS 
(
    SELECT projectid, location, SUM(totalday) AS TotalDays 
    FROM Project p 
    GROUP BY projectid, location 
) 
SELECT p1.projectId as ProjectWithMoreTotalDaysInLoc1 
FROM ProjectDays p1 
    INNER JOIN ProjectDays p2 
    ON p1.projectId = p2.projectId 
WHERE 
    p1.location = 1 and p2.location = 2 
    and p1.TotalDays > p2.TotalDays; 

爲了簡單地得到項目(而不是項目本身的列表)的計數,只要切換最終SELECT p1.projectIdSELECT COUNT(*)

Fiddle Here