のデータは別々のテーブルにあるため、car_accidents
をviolations
使用してそれらを結合する必要がありますleft join
。
これが理にかなっていることを願っています:-)
SELECT Count(*),
Avg(sl.our_cost),
Avg(sl.purchase_price)
FROM sold_leads AS sl
INNER JOIN leads AS l
ON l.id = sl.lead_id
INNER JOIN contacts AS c
ON c.lead_id = l.id
INNER JOIN drivers AS d
ON d.lead_id = l.id
LEFT JOIN
(SELECT ca1.driver_id, COUNT(*) AS cnt FROM car_accidents ca1 GROUP BY ca1.driver_id) ca
ON (c.state = 'CA' and ca.driver_id = d.id)
LEFT JOIN
(SELECT v1.driver_id, COUNT(*) AS cnt FROM violations v1 GROUP BY v1.driver_id) v
ON (c.state IN ('CA') and v.driver_id = d.id)
WHERE c.state IN( 'AK', 'AL', 'AR', 'AZ','CA', 'CO', 'CT', 'DC',
'DE', 'FL', 'GA', 'HI','IA', 'ID', 'IL', 'IN',
'KS', 'KY', 'LA', 'MD','ME', 'MI', 'MN', 'MO',
'MS', 'MT', 'NC', 'ND','NE', 'NH', 'NJ', 'NM',
'NV', 'NY', 'OH', 'OK','OR', 'PA', 'RI', 'SC',
'SD', 'TN', 'TX', 'UT','VA', 'VT', 'WA', 'WI',
'WV', 'WY' )
AND l.leg = 0
AND ( Datediff(CURRENT_DATE, d.date_of_birth) / 365 ) >= 50
AND l.create_date >= '2012-1-1'
AND IFNULL(v.cnt,0) < 2 AND ifnull(ca.cnt.0) < 2
AND (c.state IN ('FL','MD','NH','WA') OR c.IsInsured = 1)
注
状態を別のテーブルに含める方がはるかに理にかなっています。そうすれば、契約条件をそのテーブルに入れて、結合基準で使用できます。
Table state
-----------
id : varchar(2) primary key not null
country : varchar(45) not null
max_accidents : int null
max_violations : int null
must_be_insured : boolean not null
次に、クエリを次のように書き直すことができます。
SELECT Count(*),
Avg(sl.our_cost),
Avg(sl.purchase_price)
FROM sold_leads AS sl
INNER JOIN leads AS l
ON l.id = sl.lead_id
INNER JOIN contacts AS c
ON c.lead_id = l.id
INNER JOIN drivers AS d
ON d.lead_id = l.id
INNER JOIN state s ON (s.id = c.state)
LEFT JOIN
(SELECT ca1.driver_id, COUNT(*) AS cnt FROM car_accidents ca1 GROUP BY ca1.driver_id) ca
ON (s.max_accidents IS NOT NULL AND ca.driver_id = d.id)
LEFT JOIN
(SELECT v1.driver_id, COUNT(*) AS cnt FROM violations v1 GROUP BY v1.driver_id) v
ON (s.max_violations IS NOT NULL AND v.driver_id = d.id)
AND l.leg = 0
AND (Datediff(CURRENT_DATE, d.date_of_birth) / 365.25 ) >= 50
AND l.create_date >= '2012-1-1';
AND IFNULL(v.cnt,0) < 2 AND ifnull(ca.cnt.0) < 2
AND (s.must_be_insured = 0 OR c.IsInsured = 1)