将2个SQL查询连接到1个结果中

时间:2015-09-23 11:50:25

标签: mysql sql

我有两个SQL查询,我想加入一个:

 select d.full_month, COUNT(*) amount
    from fact_ticket t
    join dim_queue q on t.queue_id = q.queue_id 
    join vt_scopes s on t.scope_id = s.scope_id
    join dim_date d on t.create_date_id = d.date_id
    where q.name = 'Support'
    and year(GETDATE()) = YEAR(t.create_date)
    and s.statusname not in ('discarded', 'closed')
    group by d.full_month
    order by 1;

select d.full_month, COUNT(*) amount
from fact_ticket t
join dim_queue q on t.queue_id = q.queue_id 
join vt_scopes s on t.scope_id = s.scope_id
join dim_date d on t.create_date_id = d.date_id
where q.name = 'Support'
and year(GETDATE()) = YEAR(t.create_date)
and s.statusname in ('closed')
group by d.full_month
order by 1;

两者现在给我一个带有日期列和金额列的结果,但我希望在一个查询中获取所有内容,我将获得日期,金额1,金额2。

这样做容易吗?

2 个答案:

答案 0 :(得分:1)

您可以使用以下查询 -

SELECT d.full_month, 
COUNT(IF(s.statusname NOT IN ('discarded', 'closed'),1,NULL)) amount1, 
COUNT(IF(s.statusname IN ('closed'),1,NULL)) amount2 
    FROM fact_ticket t
    JOIN dim_queue q ON t.queue_id = q.queue_id 
    JOIN vt_scopes s ON t.scope_id = s.scope_id
    JOIN dim_date d ON t.create_date_id = d.date_id
    WHERE q.name = 'Support'
    AND YEAR(GETDATE()) = YEAR(t.create_date)
    GROUP BY d.full_month
    ORDER BY 1;

第2版:如果存在于create_date下面的查询 -

,即使你可以获得索引的好处
SELECT d.full_month, 
COUNT(IF(s.statusname NOT IN ('discarded', 'closed'),1,NULL)) amount1, 
COUNT(IF(s.statusname IN ('closed'),1,NULL)) amount2 
    FROM fact_ticket t
    JOIN dim_queue q ON t.queue_id = q.queue_id 
    JOIN vt_scopes s ON t.scope_id = s.scope_id
    JOIN dim_date d ON t.create_date_id = d.date_id
    WHERE q.name = 'Support'
    AND t.create_date>= DATE_FORMAT(NOW(),'%Y-01-01 00:00:00') AND t.create_date <= DATE_FORMAT(NOW(),'%Y-12-31 23:59:59');
    GROUP BY d.full_month
    ORDER BY 1;

答案 1 :(得分:0)

使用sum函数的另一种方法

SELECT 
  d.full_month,
  SUM(s.statusname NOT IN ('discarded', 'closed')) amount,
  SUM(s.statusname = 'closed') amount_closed 
FROM
  fact_ticket t 
  JOIN dim_queue q 
    ON t.queue_id = q.queue_id 
  JOIN vt_scopes s 
    ON t.scope_id = s.scope_id 
  JOIN dim_date d 
    ON t.create_date_id = d.date_id 
WHERE q.name = 'Support' 
  AND YEAR(GETDATE ()) = YEAR(t.create_date) 
GROUP BY d.full_month 
ORDER BY 1 ;