-- To compare the view and lead among property with feature and property without feature
-------------------------
-- District Specialist --
-------------------------
WITH
specialist_table AS (
SELECT
agent_id,
district_code,
area_code
FROM
`propertyguru-datalake-v0.propertydb_staging.my_v_property_specialist`
WHERE
type_code = 'AREA'
AND LENGTH(area_code) = 0
AND start_date <= '2018-10-01 00:00:00'
AND end_date >= '2018-10-01 00:00:00'
GROUP BY 1,2,3 ),
listing_table AS (
SELECT
id as listing_id,
district_code,
agent_id
FROM
`propertyguru-datalake-v0.propertydb_staging.my_v_listing_ds`
WHERE
_PARTITIONTIME >= "2018-10-01 00:00:00"
AND _PARTITIONTIME <= "2018-12-06 00:00:00"
AND status_code = 'ACT'
GROUP BY 1,2,3),
leadview_table AS (
SELECT
listing_id,
metric,
SUM(value) AS counts
FROM
`propertyguru-datalake-v0.datamart_v0.my_fact_leads_views`
WHERE
_PARTITIONTIME >= "2018-10-01 00:00:00"
AND _PARTITIONTIME <= "2018-12-06 00:00:00"
AND LENGTH(district_code) > 1
AND metric IN ('VIEWS','LEADS')
GROUP BY 1,2 ),
first_table AS (
SELECT
listing_table.*,
IF(specialist_table.agent_id IS NULL, 0, 1) AS spec
FROM
listing_table
LEFT JOIN
specialist_table
ON
specialist_table.agent_id = listing_table.agent_id
AND specialist_table.district_code = listing_table.district_code),
second_table AS (
SELECT
first_table.*,
IF(metric = 'VIEWS', counts, 0) view,
IF(metric = 'LEADS', counts, 0) leads
FROM
first_table
LEFT JOIN
leadview_table
USING
(listing_id))
SELECT
spec,
count(*) AS listing_count,
sum(view) AS sum_of_view,
sum(leads) AS sum_of_lead,
sum(view)/count(spec) AS view_count_per_listing,
sum(leads)/count(spec) AS lead_count_per_listing
FROM
second_table
GROUP BY 1