每日日志类型摘要

时间:2014-01-31 02:17:23

标签: mysql group-by summary

tbl_logs包含以下列:

logtimestamp, level, message

'level'可以是:错误,警告,信息,确定

我想创建一个查询,返回每天每个级别的日志数量摘要:

logdate, error_qty, warning_qty, info_qty, ok_qty

这可以在一个查询中完成吗?

我试过了:

SELECT DATE(logtimestamp) as logdate, count(*) as qty, level
FROM tbl_logs
GROUP BY logdate, level
ORDER BY logdate DESC

但是这个查询每个logdate / level组合返回一个ROW(日期将重复)。

我还尝试使用UNION:

创建查询
SELECT count(*) as error_qty ... WHERE level = 'error'...
UNION 
SELECT count(*) as warning_qty ... WHERE level = 'warning'...
...

但无法使其发挥作用。

这可以在一个查询中完成,还是我需要进行多次查询并在我的应用程序中组合输出?

1 个答案:

答案 0 :(得分:0)

SELECT DATE(logtimestamp) AS logdate,
    SUM(level = 'error') AS error_qty,
    SUM(level = 'warning') AS warning_qty,
    SUM(level = 'info') AS info_qty,
    SUM(level = 'ok') AS ok_qty
FROM tbl_logs
GROUP BY logdate
ORDER BY logdate DESC