Ok so in the below statement I am trying to take the first pi.planinfoid
selected as the first field and make it a dynamic variable in the place of the 1736
you see in the two select statements being used as additional fields.
I also need it to still return the two fields generated by the two select statements even if the value is 0 or null.
I am at my wits end thanks in advance if anyone can figure this one out.
SELECT pi.planinfoid,
pi.description,
count(DISTINCT p.planid) AS total,
sum(dm.debitamount) AS Num,
pi.minperiod,
(
SELECT count(p.planid)
FROM plans p,
planinfo pi
WHERE pi.planinfoid = p.planinfoid
AND pi.planinfoid = '1736'
AND p.closed = 0
) AS opened,
(
SELECT count(p.planid)
FROM plans p,
planinfo pi
WHERE pi.planinfoid = p.planinfoid
AND pi.planinfoid = '1736'
AND p.closed = 1
) AS closedd
FROM planinfo pi, plans p, debitmovements dm
WHERE pi.price > 0
AND p.planinfoid = pi.planinfoid
AND dm.planid = p.planid
AND p.servicestart BETWEEN '2012-01-01' AND '2013-01-01'
GROUP BY pi.description,
pi.minperiod,
pi.planinfoid
ORDER BY total DESC
That ran, but it doesnt seem that open and closed are tied to the total number in anyway,
planid plan descrip min TOTAL PRICE OPEN CLOSE
1736 Additional IP 1 146 1926 101 545
Techincally you cant have 101 still open and 545 closed if the total in that time period sold was 146, maybe its not pulling number still opened and closed for only the ones opened in that time period. the uniqe field for the 146 open would be p.planid or each one would basically have a unique p.planid, great job so far though.