MySQL帮助合并两个查询

时间:2014-09-04 23:56:33

标签: mysql

我知道这很简单,但我无法弄清楚。你能告诉我如何合并这两个,所以TotalCount的右边。


MariaDB [meta]> select `Sector`, count(*) as `Count` from meta where `Close` > `VWAP` and `Sector` != '' group by `Sector`;                                                                  +-----------------------+-------+
| Sector                | Count |
+-----------------------+-------+
| Basic Industries      |    85 |
| Capital Goods         |    90 |
| Consumer Durables     |    42 |
| Consumer Non-Durables |    63 |
| Consumer Services     |   237 |
| Energy                |    80 |
| Finance               |   233 |
| Health Care           |   165 |
| Miscellaneous         |    31 |
| Public Utilities      |   100 |
| Technology            |   162 |
| Transportation        |    35 |
+-----------------------+-------+
12 rows in set (0.00 sec)

MariaDB [meta]> select `Sector`,count(`Sector`) as `Total` from `meta` where `Sector` != '' group by `Sector`;                                                                               +-----------------------+-------+
| Sector                | Total |
+-----------------------+-------+
| Basic Industries      |   368 |
| Capital Goods         |   403 |
| Consumer Durables     |   157 |
| Consumer Non-Durables |   237 |
| Consumer Services     |   832 |
| Energy                |   382 |
| Finance               |   880 |
| Health Care           |   681 |
| Miscellaneous         |   155 |
| Public Utilities      |   264 |
| Technology            |   709 |
| Transportation        |   114 |
+-----------------------+-------+
12 rows in set (0.00 sec)

我还需要Percentage的另一列,其中count是总数的百分比。

1 个答案:

答案 0 :(得分:0)

将以下SELECT子句添加到第二个查询:

SUM(`Close` > `VWAP`) AS `Count`

它的作用是总结Close > VWAP条件为真的行数。

ANSII SQL友好(除了使用反引号)之一就是

SUM(CASE WHEN `Close` > `VWAP` THEN 1 ELSE 0 END) AS `Count`