SQL总和只是不同的值

时间:2013-11-28 23:44:16

标签: sql distinct

我有一个包含以下列的表:

plantId (pk)
unitId
maxCapacity
numberOfPlants
geographicalArea
agreementStart
agreementEnd
plantType

该表包含以下数据:

1, A1, 10, 1, 3, 2013-01-01, 2013-12-31
2, A2, 10, 1, 3, 2013-01-01, 2013-12-31
3, A1, 10, 1, 3, 2013-03-01, 2013-12-31

我想像这样查询我的表:

SELECT DISTINCT 
  plantType, 
  geographicalArea, 
  sum(maxCapacity) as maxCapacity,   
  sum(numberOfPlants) as numberOfPlants, 
  count(unitId) as idCount 
FROM 
  tbl_plant 
WHERE 
  (agreementStart <= '2013-11-28' AND 
   agreementEnd >= '2013-11-28') AND 
  plantType <> '0' AND 
  plantType = '2' AND 
  geographicalArea = '3' 
GROUP BY 
  plantType, geographicalArea 

只要结果集中每行只返回一个唯一unitId,此查询就可以正常运行。但是,如果第二次返回相同的unitId(请参阅上面的A1),我不希望sum(maxCapacity)sum(numberOfPlants)第二次包含总和,因为它有已包括它。

有关我如何更改此查询的任何想法?

1 个答案:

答案 0 :(得分:1)

使用内部查询来删除重复

SELECT plantType, geographicalArea, sum(maxCapacity) as maxCapacity, sum(numberOfPlants) as numberOfPlants, count(unitId) as idCount 
  FROM tbl_plant 
 WHERE plantId in ( 
   SELECT MAX(plantId) 
     FROM tbl_plant 
    WHERE (agreementStart <= '2013-11-28' AND agreementEnd >= '2013-11-28') 
      AND plantType <> '0' 
      AND plantType = '2' 
      AND geographicalArea = '3' 
    GROUP BY unitId
)
GROUP BY plantType, geographicalArea 
相关问题