我有一个包含两列的数据库 - result
和time
我试图计算特定月份中每个result
存在多少行。结果success
和failure
我已经设法计算每个月有多少行,但我无法获得有多少success
和多少failure
的个人数量每个月都有。
这就是我所拥有的:
SELECT result, MONTH(time) MONTH, COUNT(*) COUNT
FROM mytable
WHERE YEAR(time)=2017
GROUP BY MONTH(time);
我正在寻找一个能让我在特定月份获得12次成功和8次失败的结果。
任何帮助将不胜感激。
答案 0 :(得分:0)
使用条件聚合
SELECT result, MONTH(time) MONTH,
sum(result = 'success') as success_count,
sum(result = 'failure') as failure_count
FROM mytable
WHERE YEAR(time) = 2017
GROUP BY result, MONTH(time);
答案 1 :(得分:0)
我会使用以下查询:
SELECT,
DATE_FORMAT(time, '%m %Y') AS month_year,
SUM(CASE WHEN result = 'success' THEN 1 ELSE 0 END) AS success_count,
SUM(CASE WHEN result = 'failure' THEN 1 ELSE 0 END) AS failure_count
FROM mytable
WHERE YEAR(time) = 2017
GROUP BY
DATE_FORMAT(time, '%m %Y')
请注意,您应该仅按时间段进行汇总,而不是result
汇总,而CASE
则是<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<body>
<div data-role="page">
<div data-role="header">
<h1>Marqeta Volume Calculator</h1>
</div>
<div data-role="main" class="ui-content">
<label for="points">Monthly Transactions per Card</label>
<input type="range" name="trx" id="trx" value="25" min="1" max="175" onchange="volumeCalc()"/>
<label for="points">Monthly Active Cards</label>
<input type="range" name="cards" id="cards" value="350" min="1" max="1000" onchange="volumeCalc()"/>
<label for="points">Average Transaction Amount ($)</label>
<input type="range" name="amt" id="amt" value="12" min="1" max="1000" onchange="volumeCalc()"/>
<input type="submit" name="submit" id="submit" value="Submit" onclick="volumeCalc()"/>
<label for="points">Predicted Volume ($)</label>
<input type="number" name="total" id="total" readonly=true>
<div id="totVolume1"></div>
</div>
</div>
</body>
表达式中和的一部分。