选择分组行

时间:2009-05-14 10:49:57

标签: sql select group-by

我有一张这样的表:

Alternative |Total  |Male  |Female
a           |20     |10    |10
b           |50     |20    |30 
c           |40     |10    |30 
c           |30     |15    |15 

现在我想选择所有行和“c”替代方法进行分组。

4 个答案:

答案 0 :(得分:3)

SELECT Alternative, Sum(Total), Sum(Male), Sum(Female) 
FROM table1 
GROUP BY Alternative

答案 1 :(得分:0)

这应该足够了

SELECT Alternative, [Total] = SUM(Total), [Male] = SUM(Male), [Female] = SUM(Female)
FROM YourTable
GROUP BY Alternative

答案 2 :(得分:0)

使用group by确定分组,然后使用适当的聚合来处理其他字段。我相信在这种情况下,您希望使用sum在每个组中添加值:

select
   Alternative, sum(Total) as Total, sum(Male) as Male, sum(Female) as Female
from
   TheTable
group by
   Alternative
order by
   Alternative

答案 3 :(得分:0)

以下查询将选择所有不是“c”的行,然后将所有“c”行组合,将它们的值相加,并添加一行代表“c”的总和。我希望这就是你的意思。

SELECT *
FROM table1 
WHERE Alternative != c

UNION

SELECT Alternative, Sum(Total) as Total, Sum(Male) as Male, Sum(Female) as Female
FROM table1 
WHERE Alternative = c
GROUP BY Alternative

如果您只想将具有多个“替代”外观的任何内容分组,请使用:

SELECT Alternative, Sum(Total) as Total, Sum(Male) as Male, Sum(Female) as Female
FROM table1 
GROUP BY Alternative