MYSQL - 将两个查询合并为一个

时间:2014-03-21 16:51:35

标签: mysql

我想结合两个查询,所以它看起来像下面的欲望输出:

QUERY1

SELECT 

count(distinct case when YEAR(from_unixtime(t2.dateline)) = YEAR(CURRENT_TIMESTAMP) 
  then t1.ticketmaskid end) AS TYear, 
count(distinct case when WEEK(from_unixtime(t2.dateline)) = WEEK(CURRENT_TIMESTAMP) 
  then t1.ticketmaskid end) AS TWeek, 
count(distinct case when MONTH(from_unixtime(t2.dateline)) = MONTH(CURRENT_TIMESTAMP) 
  then t1.ticketmaskid end) AS TMonth 

FROM swtickets t1 JOIN swticketauditlogs t2 ON t1.ticketid = t2.ticketid 

WHERE FIND_IN_SET (t1.departmenttitle,'Support') AND t2.actionmsg LIKE '%Email Queue: abc.com.my%';

输出:

+-------+-------+--------+
| TYear | TWeek | TMonth |
+-------+-------+--------+
|     1 |     1 |      1 |
+-------+-------+--------+

QUERY2

SELECT 

count(distinct case when YEAR(from_unixtime(t2.dateline)) = YEAR(CURRENT_TIMESTAMP) 
  then t1.ticketmaskid end) AS TYear, 
count(distinct case when WEEK(from_unixtime(t2.dateline)) = WEEK(CURRENT_TIMESTAMP) 
  then t1.ticketmaskid end) AS TWeek, 
count(distinct case when MONTH(from_unixtime(t2.dateline)) = MONTH(CURRENT_TIMESTAMP) 
  then t1.ticketmaskid end) AS TMonth 

FROM swtickets t1 JOIN swticketauditlogs t2 ON t1.ticketid = t2.ticketid 

WHERE FIND_IN_SET (t1.departmenttitle,'Support') AND t2.actionmsg LIKE '%Email Queue: abc.com.sg%';

输出

+-------+-------+--------+
| TYear | TWeek | TMonth |
+-------+-------+--------+
|     2 |     1 |      1 |
+-------+-------+--------+

我想得到以下结果

+----------+-------+-------+--------+
|Domain    | TYear | TWeek | TMonth |
+----------+-------+-------+--------+
|abc.com.my|     2 |     1 |      1 |
+----------+-------+-------+--------+
|abc.com.sg|     1 |     1 |      1 |
+----------+-------+-------+--------+

2 个答案:

答案 0 :(得分:0)

如果2个查询返回相同的表结构... 您可以使用UNION

加入2个查询
QUERY1
UNION
QUERY2

答案 1 :(得分:0)

这是SQL中的常见操作,称为聚合。您需要使用GROUP BY

SELECT SUBSTRING_INDEX(t2.actionmsg, 'Email Queue: ', -1) as Domain,
       count(distinct case when YEAR(from_unixtime(t2.dateline)) = YEAR(CURRENT_TIMESTAMP) 
                           then t1.ticketmaskid end) AS TYear, 
       count(distinct case when WEEK(from_unixtime(t2.dateline)) = WEEK(CURRENT_TIMESTAMP) 
                           then t1.ticketmaskid end) AS TWeek, 
       count(distinct case when MONTH(from_unixtime(t2.dateline)) = MONTH(CURRENT_TIMESTAMP) 
                          then t1.ticketmaskid end) AS TMonth 
FROM   swtickets t1
 JOIN  swticketauditlogs t2 ON t1.ticketid = t2.ticketid 
WHERE  FIND_IN_SET(t1.departmenttitle, 'Support')
  AND  t2.actionmsg RLIKE 'Email Queue: abc\.com\.(my|sg)'
GROUP  BY Domain

您可以通过不限制actionmsg

将其扩展到所有可能的域
WHERE  FIND_IN_SET(t1.departmenttitle, 'Support')
  AND  t2.actionmsg RLIKE 'Email Queue: abc\.com'

然后,您将为每个可能的域获得一个单独的行。

相关问题