MySQL中具有相同表的多选不起作用

时间:2017-08-18 20:18:54

标签: mysql select multiple-select-query

我的数据库有多个选择问题。我需要做一个select,返回一种包含一些已处理数据的表,并且需要按月份的顺序排序。要做到这一点,我正在使用多个选择的mysql问题。这是我的代码:

SELECT 
    (SELECT COUNT( * ) FROM `table` WHERE `type`=1                                                                                AS 'Total',
    (SELECT COUNT( * ) FROM `table` WHERE `type`=1 and `status` = 0 and `status_cancel` = 0                                       AS 'Open',
    (SELECT COUNT( * ) FROM `table` WHERE `type`=1 and `status_cancel` = 1                                                        AS 'Cancel',
    (SELECT COUNT( * ) FROM `table` WHERE `type`=1 and `date_finish` is not null and `status_cancel` = 0                          AS 'Finish',
    (SELECT COUNT( * ) FROM `table` WHERE `type`=1 and `result` >= 0 and  `date_finish` is not null and `status_cancel` = 0       AS 'Win',
    (SELECT COUNT( * ) FROM `table` WHERE `type`=1 and `result` < 0 and `date_finish` is not null and `status_cancel` = 0         AS 'Loss'

现在它返回了我表中所有行的总数,但我不能这样做返回它按天分组,请帮帮我!

结果必须如下:

Result that i need

1 个答案:

答案 0 :(得分:0)

我想你是说当我的查询全部相当于子查询时,我如何按日期分组。我会将其改为案例陈述。试试这样的事情

SELECT  DATE(date_finish) as `date`, count(*) as 'Total', 
        SUM(CASE WHEN `status` = 0 AND `status_cancel` = 0 THEN 1 ELSE 0 END) as 'Open',
        SUM(CASE WHEN `status_cancel` = 1 THEN 1 ELSE 0 END) as 'Cancel',
        SUM(CASE WHEN `date_finish` is not null and `status_cancel` = 0 THEN 1 ELSE 0 END) as 'Finish',
        SUM(CASE WHEN `result` >= 0 AND `date_finish` is not null AND `status_cancel` = 0 THEN 1 ELSE 0 END) as 'Win',
        SUM(CASE WHEN `result` < 0 AND `date_finish` is not null AND `status_cancel` = 0 THEN 1 ELSE 0 END) as 'Loss'
from `table` 
WHERE `type` = 1 
group by DATE(date_finish)

TEST:http://rextester.com/HCRIU11065