select *, COUNT(*), DATE_FORMAT(CREATE_DATE,'%m-%Y') AS form_date
from incident_view
where (create_month = month(NOW() - INTERVAL 1 MONTH)
and (create_year = year(NOW() - INTERVAL 1 MONTH)))
OR (create_month = month(NOW() - INTERVAL 2 MONTH)
and (create_year = year(NOW() - INTERVAL 2 MONTH)))
AND CUSTOMER_COMPANY_NAME = "Company"
GROUP BY CREATE_MONTH
大家好,
我上面的查询工作正常。
我得到的结果是一些行,但重要的行是:
COUNT(*) | form_date
667 01-16
1964 02-16
我想知道是否可以比较过去2个月的两个计数,无论是上个月(02-16)>上个月的第二个月(01-16)。 如果02-16> 01-16我希望结果为真,如果不是则为假。
感谢任何帮助。
问候。
答案 0 :(得分:2)
不是按月/年分组,而是在计算计数时在CASE
或IF
中使用。
SELECT SUM(IF(create_month = MONTH(NOW() - INTERVAL 1 MONTH)
AND create_year = YEAR(NOW() - INTERVAL 1 MONTH), 1, 0)) >
SUM(IF(create_month = MONTH(NOW() - INTERVAL 2 MONTH)
AND create_year = YEAR(NOW() - INTERVAL 2 MONTH), 1, 0)) AS count_higher
FROM incident_view
WHERE customer_company_name = "Company"
如果你想要3个不同的结果大于,等于或小于,最好的方法是计算子查询中的总和,这样你就可以命名它们并使用CASE
为每个案例返回不同的值
SELECT CASE WHEN last_month > prev_month THEN 1
WHEN last_month = prev_month THEN 2
ELSE 0
END AS diff
FROM (
SELECT SUM(IF(create_month = MONTH(NOW() - INTERVAL 1 MONTH)
AND create_year = YEAR(NOW() - INTERVAL 1 MONTH), 1, 0)) AS last_month,
SUM(IF(create_month = MONTH(NOW() - INTERVAL 2 MONTH)
AND create_year = YEAR(NOW() - INTERVAL 2 MONTH), 1, 0)) AS prev_month
FROM incident_view
WHERE customer_company_name = "Company"
) AS subquery
答案 1 :(得分:0)
您可以执行类似
的操作Select max(viewcount)
FROM (select * , COUNT(*) AS viewcount,
DATE_FORMAT(CREATE_DATE,'%m-%Y') AS form_date
from incident_view
Where (create_month = month(NOW() - INTERVAL 1 MONTH) and (create_year = year(NOW() - INTERVAL 1 MONTH)))
OR (create_month = month(NOW() - INTERVAL 2 MONTH) and (create_year = year(NOW() - INTERVAL 2 MONTH)))
AND CUSTOMER_COMPANY_NAME = "Company"
GROUP BY CREATE_MONTH);