0

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

v_resident_fname(基本上是一个名字)

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

dt_note_created(日期)

所以我需要做的是,首先我想要所有的名字以及它们的计数wherei_communication_log = 0和。dt_note_created < 1332792382dt_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       |
4

1 回答 1

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
于 2013-06-18T11:45:18.090 回答