0

可能かどうかはわかりませんが、 set vars を使用して、次のクエリで日付範囲を繰り返さないようにすることはできますか? では、TY と LY を 1 回だけ宣言して、クエリで再利用しますか?

// ThisYear -- '2013-02-04 00:00:00' AND '2013-02-10 23:59:59'
// LastYear -- '2012-02-06 00:00:00' AND '2013-02-12 23:59:59'

SELECT 
  count(*) as total_num_bookings,

  SUM(if(book_date BETWEEN '2013-02-04 00:00:00' AND '2013-02-10 23:59:59', 1, 0)) AS num_bookings_ty,
  SUM(if(book_date BETWEEN '2012-02-06 00:00:00' AND '2012-02-12 23:59:59', 1, 0)) AS num_bookings_ly,
  sj.pu_country

FROM 
  pc_tech.sales_journal_default sj

WHERE (book_date BETWEEN '2013-02-04 00:00:00' AND '2013-02-10 23:59:59') OR  (book_date BETWEEN '2012-02-06 00:00:00' AND '2012-02-12 23:59:59' )
group by pu_country
order by total_num_bookings DESC
LIMIT 25;
4

1 に答える 1

1

はい:

SET @ThisYear1='2013-02-04 00:00:00', @ThisYear2='2013-02-10 23:59:59'
SET @LastYear1='2012-02-06 00:00:00', @LastYear2='2013-02-12 23:59:59'

SELECT 
  count(*) as total_num_bookings,

  SUM(if(book_date BETWEEN @ThisYear1 AND @ThisYear2, 1, 0)) AS num_bookings_ty,
...

編集

または、準備済みステートメントを使用します。

SET @ThisYear="'2013-02-04 00:00:00' AND '2013-02-10 23:59:59'";
SET @LastYear="'2012-02-06 00:00:00' AND '2013-02-12 23:59:59'";

SET @sql = CONCAT("SELECT count(*) as total_num_bookings, SUM(if(book_date BETWEEN ", @ThisYear, ", 1, 0)) AS num_bookings_ty, ...");
PREPARE stmt from @sql;
EXECUTE stmt;
...
DEALLOCATE PREPARE stmt;
于 2013-02-20T16:40:16.363 に答える