我有一张这样的桌子:
Alternative |Total |Male |Female
a |20 |10 |10
b |50 |20 |30
c |40 |10 |30
c |30 |15 |15
现在我想选择所有行和要分组的“c”替代项。
SELECT Alternative, Sum(Total), Sum(Male), Sum(Female)
FROM table1
GROUP BY Alternative
这应该足够了
SELECT Alternative, [Total] = SUM(Total), [Male] = SUM(Male), [Female] = SUM(Female)
FROM YourTable
GROUP BY Alternative
用于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
以下查询将选择所有不是“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