// Souffle - A Datalog Compiler
// Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved
// Licensed under the Universal Permissive License v 1.0 as shown at:
// - https://opensource.org/licenses/UPL
// - <souffle root>/licenses/SOUFFLE-UPL.txt

// Test finding the min, max, count of selections from a relation, and the
// min/max of a sum from two relations.

.decl a(n:symbol,x:number)

a("A",3).
a("A",4).
a("A",5).
a("A",6).
a("B",2).
a("B",3).
a("B",4).
a("D",4).

.decl res(n:symbol,x:number)
.output res()
res("min",Y)  :- Y = min Z : a(_,Z).
res("minA",Y) :- Y = min Z : a("A",Z).
res("minB",Y) :- Y = min Z : a("B",Z).
res("minC",Y) :- Y = min Z : a("C",Z).

res("minC2",Y)  :- Y = min Z : { a("C",Z) }.
res("minAB",Y)  :- Y = min Z : { a(A,Z), a(B,Z), A!=B }.
res("minAB+",Y) :- Y = min Z+Y : { a(A,Z), a(B,Y), A!=B }.

res("max",Y)  :- Y = max Z : a(_,Z).
res("maxA",Y) :- Y = max Z : a("A",Z).
res("maxB",Y) :- Y = max Z : a("B",Z).
res("maxC",Y) :- Y = max Z : a("C",Z).

res("maxC2",Y)  :- Y = max Z : { a("C",Z) }.
res("maxAB",Y)  :- Y = max Z : { a(A,Z), a(B,Z), A!=B }.
res("maxAB+",Y) :- Y = max Z+Y : { a(A,Z), a(B,Y), A!=B }.

res("count",Y)  :- Y = count : a(_,_).
res("countA",Y) :- Y = count : a("A",_).
res("countB",Y) :- Y = count : a("B",_).
res("countC",Y) :- Y = count : a("C",_).

res("countNotA",Y) :- Y = count : { a(X,_), X != "A" }.
res("countNotB",Y) :- Y = count : { a(X,_), X != "B" }.

.decl res1(n:symbol,x:number)
.output res1()
res1(X,Y) :- a(X,_), Y = min Z : a(X,Z).

.decl res2(n:symbol,x:number,y:number)
.output res2()
res2(X,Y,W) :- a(X,_), Y = min Z : a(X,Z), W = max Z : a(X,Z).

.decl res3(n:symbol,x:number)
.output res3()
res3(X,Y) :- a(X,_), Y = min Z : a(X,Z), Y = max Z : a(X,Z).
