--LaReferencia views

CREATE OR REPLACE VIEW ${usageStatsDB}.la_result_views_monthly_tmp AS
SELECT 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}.lareferencialogdistinct where action='action' and
(source_item_type='oaItem' or source_item_type='repItem')
GROUP BY entity_id, CONCAT(YEAR(timestamp), '/', LPAD(MONTH(timestamp), 2, '0')), source;

DROP TABLE IF EXISTS ${usageStatsDB}.la_views_stats_tmp;

CREATE TABLE IF NOT EXISTS ${usageStatsDB}.la_views_stats_tmp
AS SELECT 'LaReferencia' 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}.la_result_views_monthly_tmp p, ${statasDB}.datasource_oids d,
${statsDB}.result_oids ro WHERE p.source=d.oid AND p.id=ro.oid GROUP BY d.id, ro.id, month;

