I’m running a query below which won’t work as I can’t put an aggregate in a where clause, but given that it’s in a subquery I’m not entirely sure what the best way forward is from here…!
The line that doesn’t work is:
(select gradeid from commissionconsultants where UserId = ic.primaryconsultantid)
and starters = COUNT(*) ) from InvoiceCommissions ic
And the full query is as follows:
select u.username + ' ' + u.surname as UserName,
ic.primaryconsultantid,
COUNT(ic.invoiceid) as starters,
DATENAME(mm,ic.invoiceissueddate) AS [month],
DATEPART(yy,ic.invoiceissueddate) as [year],
cast(SUM((ic.value / ic.exchangerate) * (ic.primaryconsultantperc / 100)) as numeric(8,2)) AS totalvalue,
(select threshold from commissiongrades where gradeid =
(select gradeid from commissionconsultants where UserId = ic.primaryconsultantid) ) AS Threshold,
(select percentage from commissiongradevalues where gradeid =
(select gradeid from commissionconsultants where UserId = ic.primaryconsultantid)
and starters = COUNT(*) ) from InvoiceCommissions ic
inner join commissionconsultants cc on cc.userid = ic.primaryconsultantid
inner join Users u on u.UserId = ic.primaryconsultantid
group by primaryconsultantid, DATENAME(mm,invoiceissueddate), DATEPART(yy,invoiceissueddate), u.username + ' ' + u.surname
What, in essence, I am trying to do is lookup the commission percentage from a table (commissiongradevalues) based on the grade of the consultant (found in commissionconsultants) and the number of placements made in a given month.
e.g. if a consultant has made one placement in a month, they will have XX commission percentage, and if they have made two placements in a month they will have YY commission percentage.
Any ideas?
I suggest to use just one main subquery when you do grouping and then do all joins. It’s hard to write query without test data.
Anyway as far as I see – you’r using two subqueries on
commissionconsultantsand actually you need only one join on this table.