SQL Query在不同条件下比较两行

时间:2013-05-16 05:29:52

标签: sql-server

我需要一个查询来检索下表中的值

enter image description here

我需要一个查询来计算位置1中总和(总天数)大于位置2中的总和(总天数)的项目总数。

请帮帮我

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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.projectId切换为SELECT COUNT(*)

Fiddle Here

答案 2 :(得分: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