我一直在从事一个包含大量汇总统计数据的项目。对我很有帮助的一件事是设置一个变量,该变量集等于出现在每一行的查询结果。就像是
declare @totalpop int
set @totalpop = select count(*) as [population]
from myTable
select sex, count(sex), @totalpop
from myTable
忍者编辑我尝试过的查询,但失败了。错误是关键字选择附近的语法不正确
SELECT gender, count(gender) AS countGender, @totalPop AS totalPop
FROM myTable
GROUP BY gender
根据您的最后一段,这似乎是您想要的:
SELECT tsum.*, sum(cnt) over (partition by NULL) as TotalPop
FROM (SELECT gender, count(*) as cnt
FROM t
GROUP BY gender
) tsum
带有“over”子句的表达式是一个将所有窗口相加的窗口函数。
SELECT gender, count(gender), @totalPop
FROM myTable
由于您使用@
的是变量,我假设您使用的是 Sql Server。以下脚本返回一行,包含 3 列(每个计数一列)。我知道这不完全符合您的要求,但我想这是返回相同信息的一种简单方法:
DECLARE @COUNT_TOTAL INT;
DECLARE @COUNT_MALE INT;
DECLARE @COUNT_FEMALE INT;
SELECT @COUNT_TOTAL = COUNT(*)
@COUNT_MALE = SUM(CASE WHEN gender='MALE' THEN 1 ELSE 0 END),
@COUNT_FEMALE = SUM(CASE WHEN gender='FEMALE' THEN 1 ELSE 0 END),
FROM myTable;
SELECT @COUNT_TOTAL AS [COUNT_TOTAL]
, @COUNT_MALE AS [COUNT_MALE]
, @COUNT_FEMALE AS [COUNT_FEMALE];