我正在尝试计算两组数据,这些数据列在相同的表名下,具有特定的日期范围。
表'事件'
u_id event Create 123 F_log 25-Sep-16 127 C_log 25-Sep-16 123 F_log 25-Sep-16 126 F_log 25-Sep-16 185 M_log 25-Sep-16 146 D_log 25-Sep-16 173 F_log 26-Sep-16 183 C_log 26-Sep-16 193 F_log 26-Sep-16 204 M_log 27-Sep-16 214 D_log 27-Sep-16 225 F_log 27-Sep-16
预期结果
Created F_log C_log 25-Sep-16 2 1 26-Sep-16 2 1
我的查询没有给出正确的结果;
SELECT COUNT (DISTINCT e.user_id) AS Flash,
COUNT (DISTINCT et.user_id) AS Client,
TO_CHAR (e.created) AS Date_created
FROM events e INNER JOIN events et ON e.user_id = et.user_id
WHERE e.created BETWEEN '25-SEP-15' AND '27-SEP-15'
AND e.event_type = 'Flash C log'
AND et.event_type = 'Client C log'
GROUP BY TO_CHAR (e.created);
答案 0 :(得分:0)
<强>查询强>
SELECT t.`Create`,
SUM(CASE WHEN t.`F_log` > 0 THEN 1 ELSE 0 END) as `F_log`,
SUM(CASE WHEN t.`C_log` > 0 THEN 1 ELSE 0 END) as `C_log` FROM(
select `u_id`, `Create`,
SUM(CASE WHEN `event` = 'F_log' THEN 1 ELSE 0 END) AS `F_log`,
SUM(CASE WHEN `event` = 'C_log' THEN 1 ELSE 0 END) AS `C_log`
FROM `Event`
GROUP BY `u_id`, `Create`
)t
GROUP BY t.`Create`;
答案 1 :(得分:0)
COUNT必须在单独的子查询中完成。这应该有用。
SELECT DISTINCT E.created,F.flash,C.client
FROM events E
LEFT JOIN (
SELECT created,COUNT(DISTINCT user_id) as flash
FROM events
WHERE event_type LIKE 'Flash C log'
GROUP BY created
) F
ON F.created = E.created
LEFT JOIN (
SELECT Created,COUNT(DISTINCT user_id) as client
FROM events
WHERE event_type LIKE 'Client C log'
GROUP BY created
) C
ON C.created = E.created
WHERE E.created BETWEEN '2016-09-25' AND '2016-09-27'
编辑:截至您的评论,我提出了一个问题,即为每个日期添加一列不同的组合用户ID与客户端和Flash日志。我添加了一些小数据来测试。
SELECT DISTINCT E.created,F.flash,C.client,FC.combined
FROM events E
LEFT JOIN (
SELECT created,COUNT(DISTINCT user_id) as flash
FROM events
WHERE event_type LIKE 'Flash C log'
GROUP BY created
) F
ON F.created = E.created
LEFT JOIN (
SELECT Created,COUNT(DISTINCT user_id) as client
FROM events
WHERE event_type LIKE 'Client C log'
GROUP BY created
) C
ON C.created = E.created
LEFT JOIN (
SELECT Created,COUNT(DISTINCT user_id) as combined
FROM events
WHERE event_type LIKE 'Client C log' OR event_type LIKE 'Flash C log'
GROUP BY created
) FC
ON FC.created = E.created
WHERE E.created BETWEEN '2016-09-25' AND '2016-09-27'
答案 2 :(得分:0)
选择to_char(强制转换(创建为日期),'YYYY-MM-DD')作为Report_date, count(distinct(event_type in('Flash C Log')then user_id else 0 end))作为Flash_Log, count(distinct(case_type ='Client C Log')然后user_id else 0 end))作为Client_Log 来自事件e 在'25 -SEP-16'和'27 -SEP-16'之间创建的地方 group by to_char(cast(创建为日期),'YYYY-MM-DD') 按to_char排序(强制转换(创建为日期),'YYYY-MM-DD');