但是我对查询很难过。
查询
<div ng-init="test=false">
<div id="child1">
<p ng-click="$parent.test=!$parent.test">
Click!
</p>
</div>
<div id="child2">
<p ng-if="$parent.test">
Clicked..
</p>
</div>
</div>
结果
结果中,2016年男性人数为4人,女性人数为8人。2017年,我希望2017年的男性人数加上男性人数2017年,意味着2017年男性人数将为5人,与女性人数相同和总数。我在下面提供了一个结果应该是什么样子的图片。你能帮我解决这个问题,让我继续做图表吗?或者还有其他方法可以达到这个目的吗?
答案 0 :(得分:2)
试试这个:
SELECT
year_added,
@malecount_v := @malecount_v + malecount as malecount,
@femalecount_v := @femalecount_v + femalecount as femalecount,
@totalcount_v := @totalcount_v + totalcount as totalcount
FROM (
SELECT
year_added,
COUNT(case when gender='Male' then 1 end) as malecount,
COUNT(case when gender='Female' then 1 end) as femalecount,
COUNT(*) as totalcount
FROM tbl
WHERE status = 1
GROUP BY year_added
ORDER BY year_added
) t1
CROSS JOIN (SELECT @malecount_v := 0, @femalecount_v := 0, @totalcount_v := 0) t2
答案 1 :(得分:0)
在Mysql中,您可以使用variables来完成,例如:
SELECT
year_added,
(@iMalecount := (COUNT(CASE WHEN gender = 'Male' THEN 1 END) + @iMalecount)) AS malecount,
(@iFemalecount := (COUNT(CASE WHEN gender = 'Female' THEN 1 END) + @iFemalecount)) AS femalecount,
(@iTotalcount := (COUNT(gender) + @iTotalcount)) AS totalcount
FROM tbl
WHERE status = 1
GROUP BY year_added
但不是100%,因为您可以在文档中阅读。
在其他SQL风格中,您可能需要一个存储过程。
答案 2 :(得分:-1)
你可以简单地使用
WITH TableCount AS
(
SELECT
year_added,
COUNT(case when gender='Male' then 1 end) as malecount,
COUNT(case when gender='Female' then 1 end) as femalecount,
COUNT(*) as totalcount
FROM tbl
WHERE status = 1
GROUP BY year_added
)
之后使用以下查询
SELECT
SUM(malecount) as 'malecount',
SUM(femalecount) as 'femalecount',
SUM(totalcount) as 'totalcount'
FROM TableCount
如果您使用MySql
,可以使用临时表来执行类似CTE的操作
CREATE TEMPORARY TABLE IF NOT EXISTS TableCount AS (
SELECT
year_added,
COUNT(case when gender='Male' then 1 end) as malecount,
COUNT(case when gender='Female' then 1 end) as femalecount,
COUNT(*) as totalcount
FROM tbl
WHERE status = 1
GROUP BY year_added
)
然后你可以使用上面的查询
SELECT
SUM(malecount) as 'malecount',
SUM(femalecount) as 'femalecount',
SUM(totalcount) as 'totalcount'
FROM TableCount
创建表时可以使用TEMPORARY关键字。临时的 table仅对当前会话可见,并被删除 会话关闭时自动这意味着两个 不同的会话可以使用相同的临时表名称 相互冲突或与现有的非TEMPORARY表冲突 同名。 (现有表隐藏到临时表之前 被删除。)要创建临时表,您必须具有CREATE TEMPORARY TABLES特权。
通过使用临时表概念,您可以在MySql中实现常见的表表达式功能