0

我有以下查询得到一些我想按属性“状态”分组的结果。我尝试了不同的子查询,但它们没有用,我有点受阻。SQL 是:

    SELECT state, id_candidate_basic, MAX( DATE )  FROM `candidate_state` 
    WHERE `date` <= '2013-09-06 00:00:00' GROUP BY id_candidate_basic
    ORDER BY `candidate_state`.`id_candidate_basic` DESC

这当前返回:

在此处输入图像描述

我会得到每个州的计数(*)。示例:F、14 I、10 O、9

4

1 回答 1

0
SELECT  state, 
        id_candidate_basic, 
        MAX( DATE ),
        COALESCE(totalCount, 0) totalCount
FROM    `candidate_state` 
        LEFT JOIN 
        (
            SELECT  state, COUNT(*) totalCount
            FROM    candidate_state
            WHERE   `date` <= '2013-09-06 00:00:00' 
            GROUP   BY state
        )   ON candidate_state.state = b.state
WHERE   `date` <= '2013-09-06 00:00:00' 
GROUP   BY id_candidate_basic
ORDER   BY `candidate_state`.`id_candidate_basic` DESC
于 2013-09-10T15:57:41.110 回答