如何将三个表结果加入到一个结果中

时间:2017-07-25 06:42:58

标签: mysql sql

我在同一个表中使用不同的where语句

跟踪了三个结果
  SELECT count(*) as LONG_TERM_LEASE_2017_Apirl
  FROM drivenow.rent 
  where (rentalterm="Both" OR rentalterm="Long") AND (created_at BETWEEN '2017-04-01' AND '2017-04-30');

SELECT count(*) as LONG_TERM_LEASE_2017_May 
FROM drivenow.rent 
where (rentalterm="Both" OR rentalterm="Long") AND (created_at BETWEEN '2017-05-01' AND '2017-05-30');

SELECT count(*) as LONG_TERM_LEASE_2017_June
FROM drivenow.rent
WHERE (rentalterm="both" OR  rentalterm="Long" )AND (created_at BETWEEN '2017-06-01' AND '2017-06-30');

我希望在我的SQL结果中并排显示类似的内容

LONG_TERM_LEASE_2017_Apirl|LONG_TERM_LEASE_2017_May|LONG_TERM_LEASE_2017_June

我怎样才能做到这一点?对不起,我是编程初学者。

3 个答案:

答案 0 :(得分:1)

SELECT 
COUNT(CASE WHEN (rentalterm="Both" OR rentalterm="Long") AND (created_at BETWEEN '2017-04-01' AND '2017-04-30') then 1 ELSE NULL END) as LONG_TERM_LEASE_2017_Apirl,
COUNT(CASE WHEN (rentalterm="Both" OR rentalterm="Long") AND (created_at BETWEEN '2017-05-01' AND '2017-05-30'); then 1 ELSE NULL END) as LONG_TERM_LEASE_2017_May ,
COUNT(CASE WHEN (rentalterm="both" OR  rentalterm="Long" )AND (created_at BETWEEN '2017-06-01' AND '2017-06-30') then 1 ELSE NULL END) as LONG_TERM_LEASE_2017_June
from drivenow.rent ;

答案 1 :(得分:1)

你可以cross join这三个选择,但事实上你只需要一个选择使用条件聚合

 SELECT
    count(case when created_at BETWEEN '2017-04-01' AND '2017-04-30' then 1 end) as LONG_TERM_LEASE_2017_Apirl,
    count(case when created_at BETWEEN '2017-05-01' AND '2017-05-30' then 1 end) as LONG_TERM_LEASE_2017_May,
    count(case when created_at BETWEEN '2017-06-01' AND '2017-06-30' then 1 end) as LONG_TERM_LEASE_2017_June
  FROM drivenow.rent 
  where (rentalterm="Both" OR rentalterm="Long") 
    AND (created_at BETWEEN '2017-04-01' AND '2017-06-30' );

案例返回的1只是计数的虚拟值。 而不是count你也可以使用这样的总和:

sum(case when created_at BETWEEN '2017-04-01' AND '2017-04-30' then 1 else 0 end)

答案 2 :(得分:1)

试试这样:

select
SUM(case when (rentalterm="Both" OR rentalterm="Long") AND (created_at BETWEEN '2017-04-01' AND '2017-04-30') then 1 else 0) as LONG_TERM_LEASE_2017_Apirl,
SUM(case when (rentalterm="Both" OR rentalterm="Long") AND (created_at BETWEEN '2017-05-01' AND '2017-05-30') then 1 else 0) as LONG_TERM_LEASE_2017_May,
SUM(case when (rentalterm="both" OR  rentalterm="Long" )AND (created_at BETWEEN '2017-06-01' AND '2017-06-30') then 1 else 0) as LONG_TERM_LEASE_2017_June
FROM drivenow.rent 
WHERE(rentalterm="Both" OR rentalterm="Long") AND (created_at BETWEEN '2017-04-01' AND '2017-06-30') then 1 else 0)