-- find all products manufactured by companies headquartered in san_jose.  
-- q(y) :- producesproduct(x,y), headquarteredin(x,'san_jose')
SELECT u.value, or_aggregate(u.p * v.p) AS prob
FROM Nell u, Nell v
WHERE u.relation = 'concept:producesproduct' AND v.relation='concept:headquarteredin'
AND u.entity=v.entity AND v.value = 'concept:city:san_jose'
GROUP BY u.value
ORDER BY prob DESC;

-- Find all products made by companies without competitors.
-- cc(x) :- competeswith(x,y)   /* all companies with some competitor */
-- q(y) :- producesproduct(x,y), not cc(x)
SELECT u.value, or_aggregate(u.p * (1-w.p)) AS prob
FROM Nell u, (
	SELECT DISTINCT v.entity, 0 AS p
	FROM Nell v
	WHERE v.relation = 'concept:producesproduct'
	AND v.entity NOT IN (SELECT DISTINCT z.entity FROM Nell z WHERE z.relation = 'concept:competeswith')
	UNION
	SELECT v.entity, or_aggregate(v.p) AS p
	FROM Nell v
	WHERE v.relation = 'concept:competeswith'
	GROUP BY v.entity
) w
WHERE u.relation = 'concept:producesproduct' AND u.entity = w.entity
GROUP BY u.value
ORDER BY prob DESC;

-- Find all cities that are headquarters of some company that have at
-- leASt one competitor AND manufacture at leASt one product.
-- q(y) :- headquarteredin(x,y),competeswith(x,z),producesproduct(x,u)

SELECT u.value, or_aggregate(u.p*v.p*w.p) AS prob
FROM Nell u,
(SELECT v.entity, or_aggregate(v.p) AS p
	FROM Nell v
	WHERE v.relation = 'concept:competeswith'
	GROUP BY v.entity) AS v,
(SELECT w.entity, or_aggregate(w.p) AS p
	FROM Nell w
	WHERE w.relation = 'concept:producesproduct'
	GROUP BY w.entity) AS w
WHERE u.relation = 'concept:headquarteredin'
AND u.entity = v.entity AND u.entity = w.entity
GROUP BY u.value
ORDER BY prob DESC;
