Hi,
I am developing a SQL calc. view. I reach to a level where I have my data like:
customer country month cost
c001 US 201506 -100
c001 DK 201506 -100
c001 DE 201506 -50
c001 FR 201507 -200
c001 UK 201507 -50
out of above dataset, I need to get below results:
customer country month cost
c001 DK 201506 -100
c001 FR 201507 -200
that is 'within each month', taking 'lowest cost' generating 'country' for each customer.
CATCH: in this example, we can see that in 201506, cost -100 is same for US and DK. In this case only taking either one, not both.
WHAT I've tried so far:
SELECT "customer" as "custM", "month" as "monthM", "country" as "countryM", "cost" as "costM"
FROM "mytable" as "M"
INNER JOIN
(
SELECT "customer" as "custS", "month" as "monthS", MIN("costSUM") AS "costMIN"
FROM
(SELECT distinct "customer", "country", "month", sum("cost") as "costSUM" FROM "mytable"
GROUP BY "customer", "country", "month")
GROUP BY "customer","month"
) as "S"
ON "M"."customer" = "S"."custS" AND "M"."month" = "S"."monthS" AND "M"."cost"= "S"."costMIN"
the above SQL gives me result like:
c001 US 201506 -100
c001 DK 201506 -100
c001 FR 201507 -200
but i need either like:
c001 DK 201506 -100
c001 FR 201507 -200
OR like:
c001 US 201506 -100
c001 FR 201507 -200
I much appreciate your help how to write SQL to solve this issue.
best regards
Ahmad