--B2SHARE

DROP view IF EXISTS ${usageStatsDB}.b2share_result_views_monthly_tmp;

DROP view IF EXISTS ${usageStatsDB}.b2share_result_downloads_monthly_tmp";

DROP TABLE IF EXISTS ${usageStatsDB}.b2share_views_stats_tmp;

DROP TABLE IF EXISTS ${usageStatsDB}.b2share_downloads_stats_tmp;

CREATE OR REPLACE VIEW ${usageStatsDB}.b2share_result_views_monthly_tmp
AS SELECT entity_id, reflect('java.net.URLDecoder', 'decode', entity_id) AS id,
COUNT(entity_id) as views, SUM(CASE WHEN referrer_name LIKE '%openaire%' THEN 1 ELSE 0 END) AS openaire_referrer,
CONCAT(YEAR(timestamp), '/', LPAD(MONTH(timestamp), 2, '0')) AS month, source
FROM ${usageStatsDB}.piwiklogdistinct
WHERE action='action' and (source_item_type='oaItem' or source_item_type='repItem') and source=412
GROUP BY entity_id, CONCAT(YEAR(timestamp), '/', LPAD(MONTH(timestamp), 2, '0')), source;

CREATE TABLE IF NOT EXISTS ${usageStatsDB}.b2share_views_stats_tmp AS
SELECT 'B2SHARE' as source, d.id as repository_id, ro.id as result_id, month as date,
max(views) AS count, max(openaire_referrer) AS openaire
FROM ${usageStatsDB}.b2share_result_views_monthly_tmp p, ${statsDB}.datasource d, ${statsDB}.result_oids ro
WHERE p.id=ro.oid and d.id='re3data_____::ad3609c351bd520edf6f10f5e0d9b877'
GROUP BY d.id, ro.id, month;

CREATE OR REPLACE VIEW ${usageStatsDB}.b2share_result_downloads_monthly_tmp
AS SELECT entity_id, reflect('java.net.URLDecoder', 'decode', entity_id) AS id,
COUNT(entity_id) as views, SUM(CASE WHEN referrer_name LIKE '%openaire%' THEN 1 ELSE 0 END) AS openaire_referrer,
CONCAT(YEAR(timestamp), '/', LPAD(MONTH(timestamp), 2, '0')) AS month, source
FROM ${usageStatsDB}.piwiklogdistinct
WHERE action='download' and (source_item_type='oaItem' or source_item_type='repItem') and source=412
GROUP BY entity_id, CONCAT(YEAR(timestamp), '/', LPAD(MONTH(timestamp), 2, '0')), source;

CREATE TABLE IF NOT EXISTS ${usageStatsDB}.b2share_downloads_stats_tmp AS
SELECT 'B2SHARE' as source, d.id as repository_id, ro.id as result_id, month as date,
max(views) AS count, max(openaire_referrer) AS openaire FROM ${usageStatsDB}.b2share_result_downloads_monthly_tmp p,
${statsDB}.datasource d, ${statsDB}.result_oids ro
WHERE p.id=ro.oid and d.id='re3data_____::ad3609c351bd520edf6f10f5e0d9b877'
GROUP BY d.id, ro.id, month;

DROP view IF EXISTS ${usageStatsDB}.b2share_result_views_monthly_tmp;

DROP view IF EXISTS ${usageStatsDB}.b2share_result_downloads_monthly_tmp";
