在一列的基础上加入两个查询结果

时间:2013-06-18 11:41:24

标签: mysql

我有这样的表结构。表名为z_notes

v_resident_fname(基本上是一个名字)

i_communication_log(布尔值,包含0或1,0表示常规注释,1表示关键注释)

dt_note_created(日期)

所以我需要做的是,首先我想要所有的名字以及i_communication_log = 0dt_note_created < 1332792382以及dt_note_create > 1332792382的数量。

所以对此的查询是:

SELECT v_resident_fname as Name, COUNT( * ) AS Critical_Notes 
FROM z_notes
WHERE dt_note_created >1332792382
AND dt_note_created <1332892382
AND `i_communication_log` = 1
GROUP BY v_resident_fname

返回:

______________________
|Name |Critical_Notes|


| abc |      7       |

| xyz |      4       |

另一个查询是相同的,但是i_communcation_log = 0

SELECT v_resident_fname as Name, COUNT( * ) AS Routine_Notes 
FROM z_notes
WHERE dt_note_created >1332792382
AND dt_note_created <1332892382
AND `i_communication_log` = 0
GROUP BY v_resident_fname

_____________________
|Name |Routine_Notes |

| abc |      3       |

| xyz |      4       |

我想在Name的基础上将这两个查询组合为一个查询,以便最终结果如下:

____________________________________
|Name |Critical_Notes|Routine_Notes|

| abc |      7       |     3       |

| xyz |      4       |     4       |

1 个答案:

答案 0 :(得分:0)

试试这个:

SELECT
    v_resident_fname as Name,
    SUM(CASE i_communication_log WHEN 1 THEN 1 ELSE 0 END) AS Critical_Notes,
    SUM(CASE i_communication_log WHEN 0 THEN 1 ELSE 0 END) AS Routine_Notes
FROM z_notes
WHERE dt_note_created >1332792382
AND dt_note_created <1332892382
GROUP BY v_resident_fname