How to use aggregate function? - sql

I have the following query:
SELECT dbo.saleDocumentDetails.ID,
dbo.saleDocumentDetails.DocumentID,
dbo.saleDocumentDetails.invProductID,
dbo.saleDocumentDetails.Qty,
dbo.saleDocumentDetails.QtyConfirmed,
dbo.saleDocumentDetails.AmountPrice,
dbo.saleDocumentDetails.AmountUserPrice,
dbo.saleDocumentDetails.AmountCost,
dbo.saleDocumentDetails.RespiteDays,
dbo.saleDocumentDetails.Date_UpdateLast,
CASE
WHEN io1.Code = '33' THEN SUM(idd.Qty)
ELSE SUM(0)
END AS Qty_BackSale,
CASE
WHEN io1.Code = '41' THEN SUM(idd.Qty)
ELSE SUM(0)
END AS Qty_Stock
FROM dbo.saleDocuments
INNER JOIN dbo.saleDocumentDetails
ON dbo.saleDocuments.ID = dbo.saleDocumentDetails.DocumentID
LEFT OUTER JOIN dbo.invDocumentDetails AS idd
ON dbo.saleDocumentDetails.ID = idd.saleDocumentDetailID
LEFT OUTER JOIN dbo.invDocuments AS id2
ON id2.ID = idd.invDocumentID
LEFT JOIN dbo.invOperations AS io1
ON (io1.ID = id2.invOperationID)
WHERE (dbo.saleDocumentDetails.ID = 1295617)
GROUP BY
dbo.saleDocumentDetails.ID,
dbo.saleDocumentDetails.DocumentID,
dbo.saleDocumentDetails.invProductID,
dbo.saleDocumentDetails.Qty,
dbo.saleDocumentDetails.QtyConfirmed,
dbo.saleDocumentDetails.AmountPrice,
dbo.saleDocumentDetails.AmountUserPrice,
dbo.saleDocumentDetails.AmountCost,
dbo.saleDocumentDetails.RespiteDays,
dbo.saleDocumentDetails.Date_UpdateLast,
io1.Code
its result is:
I would like to achieve:
How should I change the query?

As mentioned JRLambert, move SUM() outside CASE, and remove io1.Code from GROUP BY

Move the SUM() in your CASE statements outside of the CASE:
SELECT
dbo.saleDocumentDetails.ID,
dbo.saleDocumentDetails.DocumentID,
dbo.saleDocumentDetails.invProductID,
dbo.saleDocumentDetails.Qty,
dbo.saleDocumentDetails.QtyConfirmed,
dbo.saleDocumentDetails.AmountPrice,
dbo.saleDocumentDetails.AmountUserPrice,
dbo.saleDocumentDetails.AmountCost,
dbo.saleDocumentDetails.RespiteDays,
dbo.saleDocumentDetails.Date_UpdateLast,
SUM(CASE
WHEN io1.Code = '33' THEN idd.Qty
ELSE 0
END) AS Qty_BackSale,
SUM(CASE
WHEN io1.Code = '41' THEN idd.Qty
ELSE 0
END) AS Qty_Stock
FROM
dbo.saleDocuments
INNER JOIN dbo.saleDocumentDetails
ON dbo.saleDocuments.ID = dbo.saleDocumentDetails.DocumentID
LEFT OUTER JOIN dbo.invDocumentDetails AS idd
ON dbo.saleDocumentDetails.ID = idd.saleDocumentDetailID
LEFT OUTER JOIN dbo.invDocuments AS id2
ON id2.ID = idd.invDocumentID
LEFT JOIN dbo.invOperations AS io1
ON (io1.ID = id2.invOperationID)
WHERE
(dbo.saleDocumentDetails.ID = 1295617)
GROUP BY
dbo.saleDocumentDetails.ID,
dbo.saleDocumentDetails.DocumentID,
dbo.saleDocumentDetails.invProductID,
dbo.saleDocumentDetails.Qty,
dbo.saleDocumentDetails.QtyConfirmed,
dbo.saleDocumentDetails.AmountPrice,
dbo.saleDocumentDetails.AmountUserPrice,
dbo.saleDocumentDetails.AmountCost,
dbo.saleDocumentDetails.RespiteDays,
dbo.saleDocumentDetails.Date_UpdateLast,
io1.Code;

Have you tried to remove group by dbo.saleDocumentDetails.ID ?

Related

Group by + Select Case

I try to query this code but i got the error massage.
"ORA-00979: not a GROUP BY expression"
Can we use case SUM and Max in group by function.
SELECT PLAN.MFGNO "MFGNO",
PROCESSMASTER.PART_NO "PART_NO",
PROCESS.MED_PROC_CD "M_PROCESS",
MAX(PLAN.PLAN_START) "PLAN_START_DATE",
MAX(PLAN.PLAN_END) "PLAN_END_DATE",
MAX(PLAN.ACT_START) "ACT_START_DATE",
MAX(PLAN.ACT_END) "ACT_END_DATE",
(CASE WHEN PROCESSMASTER.COMP_FLG =1 AND PROCESS.MED_PROC_CD='OUT-P' THEN SUM(SUB_PRO.HACYUKIN)
ELSE MAX(SUB_PRO.HACYUKIN)
END) "SUB_TOTAL_PRICE",
--SUM(SUB_PRO.HACYUKIN) "SUB_TOTAL_PRICE",
MAX(SUB_PRO.SICD) "SUB_CODE",
MAX(PROCESSMASTER.PROC_REM) "DE_PROCESS"
FROM T_PLANDATA PLAN
INNER JOIN T_PROCESSNO PROCESSMASTER
ON PLAN.BARCODE = PROCESSMASTER.BARCODE
INNER JOIN T_PLANNED_PROCESS PROCESS
ON PROCESSMASTER.PROCESS_CD = PROCESS.PLAN_PROC_CD
INNER JOIN KEIKAKUMST SUB_PRO
ON PROCESSMASTER.BARCODE = SUB_PRO.KMSEQNO
WHERE PLAN.MFGNO ='T21-F2D1-10034'
GROUP BY PLAN.MFGNO,
PROCESSMASTER.PART_NO,
PROCESS.MED_PROC_CD;
Can we use case SUM and Max in group by function.
Yes
However, your problem is that you use PROCESSMASTER.COMP_FLG =1 AND PROCESS.MED_PROC_CD = 'OUT-P' inside the CASE expression and neither PROCESSMASTER.COMP_FLG nor PROCESS.MED_PROC_CD are in the GROUP BY clause or inside of an aggregation function.
You either want:
SELECT PLAN.MFGNO "MFGNO",
PROCESSMASTER.PART_NO "PART_NO",
PROCESS.MED_PROC_CD "M_PROCESS",
MAX(PLAN.PLAN_START) "PLAN_START_DATE",
MAX(PLAN.PLAN_END) "PLAN_END_DATE",
MAX(PLAN.ACT_START) "ACT_START_DATE",
MAX(PLAN.ACT_END) "ACT_END_DATE",
(CASE WHEN PROCESSMASTER.COMP_FLG =1 AND PROCESS.MED_PROC_CD='OUT-P' THEN SUM(SUB_PRO.HACYUKIN)
ELSE MAX(SUB_PRO.HACYUKIN)
END) "SUB_TOTAL_PRICE",
--SUM(SUB_PRO.HACYUKIN) "SUB_TOTAL_PRICE",
MAX(SUB_PRO.SICD) "SUB_CODE",
MAX(PROCESSMASTER.PROC_REM) "DE_PROCESS"
FROM T_PLANDATA PLAN
INNER JOIN T_PROCESSNO PROCESSMASTER
ON PLAN.BARCODE = PROCESSMASTER.BARCODE
INNER JOIN T_PLANNED_PROCESS PROCESS
ON PROCESSMASTER.PROCESS_CD = PROCESS.PLAN_PROC_CD
INNER JOIN KEIKAKUMST SUB_PRO
ON PROCESSMASTER.BARCODE = SUB_PRO.KMSEQNO
WHERE PLAN.MFGNO ='T21-F2D1-10034'
GROUP BY PLAN.MFGNO,
PROCESSMASTER.PART_NO,
PROCESS.MED_PROC_CD,
PROCESSMASTER.COMP_FLG, -- Add to the group by clause
PROCESS.MED_PROC_CD -- Add to the group by clause
;
or something like:
SELECT PLAN.MFGNO "MFGNO",
PROCESSMASTER.PART_NO "PART_NO",
PROCESS.MED_PROC_CD "M_PROCESS",
MAX(PLAN.PLAN_START) "PLAN_START_DATE",
MAX(PLAN.PLAN_END) "PLAN_END_DATE",
MAX(PLAN.ACT_START) "ACT_START_DATE",
MAX(PLAN.ACT_END) "ACT_END_DATE",
CASE
WHEN MAX(PROCESSMASTER.COMP_FLG) = 1
AND COUNT(CASE WHEN PROCESS.MED_PROC_CD = 'OUT-P' THEN 1 END) > 0
THEN SUM(SUB_PRO.HACYUKIN)
ELSE MAX(SUB_PRO.HACYUKIN)
END "SUB_TOTAL_PRICE",
--SUM(SUB_PRO.HACYUKIN) "SUB_TOTAL_PRICE",
MAX(SUB_PRO.SICD) "SUB_CODE",
MAX(PROCESSMASTER.PROC_REM) "DE_PROCESS"
FROM T_PLANDATA PLAN
INNER JOIN T_PROCESSNO PROCESSMASTER
ON PLAN.BARCODE = PROCESSMASTER.BARCODE
INNER JOIN T_PLANNED_PROCESS PROCESS
ON PROCESSMASTER.PROCESS_CD = PROCESS.PLAN_PROC_CD
INNER JOIN KEIKAKUMST SUB_PRO
ON PROCESSMASTER.BARCODE = SUB_PRO.KMSEQNO
WHERE PLAN.MFGNO ='T21-F2D1-10034'
GROUP BY PLAN.MFGNO,
PROCESSMASTER.PART_NO,
PROCESS.MED_PROC_CD;
Note: this is untested as you have not provided a minimal representative example of your tables or data to test against.

Joining two aggregate queries from the same table - SQL Server

I have two queries, both are aggregated from the same table. I'm not sure if I have to join these two queries together or if it can be done with one select statement. The goal is to output a table that aggregates total charges and total refunds for each student.
Query #1:
select
s.learners_id, sum(charge.total_amount) charge_amount
from
fact_student_transactions_t charge
inner join
dim_students_t s on s.students_sk_id = charge.students_sk_id
left join
object_statuses_t os on os.object_statusid = charge.transaction_status_id
where
os.status_name = 'Success'
and charge.tran_type = 'CHARGE'
and charge.curr_in = 1
group by
s.learners_id
Query #2:
select
s.learners_id, sum(refund.total_amount) refund_amount
from
fact_student_transactions_t refund
inner join
dim_students_t s on s.students_sk_id = refund.students_sk_id
left join
object_statuses_t os on os.object_statusid = refund.transaction_status_id
where
os.status_name = 'Success'
and refund.tran_type = 'Refund'
and refund.trans_description not in ('Amount Successfully Transfered to Prepaid Balance.', 'Amount Successfully Transfered.')
and refund.payment_method != 'Transfer'
and refund.curr_in = 1
group by
s.learners_id
You can use conditional aggregation. Also, because of the nature of the where clause, the left join is unnecessary -- the unmatched records are filtered out anyway.
So:
select s.learners_id,
sum(case when st.tran_type = 'CHARGE' then st.total_amount else 0 end) as charge_amount,
sum(case when st.tran_type = 'Refund' and
st.trans_description not in ('Amount Successfully Transfered to Prepaid Balance.', 'Amount Successfully Transfered.')
and
st.payment_method <> 'Transfer'
then st.total_amount else 0
end) as refund_amount
from fact_student_transactions_t st join
dim_students_t s
on s.students_sk_id = t.students_sk_id join
object_statuses_t os
on os.object_statusid = t.transaction_status_id
where os.status_name = 'Success' and
st.curr_in = 1 and
st.tran_type in ('CHARGE', 'Refund')
group by s.learners_id

Column 'sip.sip.Application.Id' is invalid in the select list

i have an query that is returning "Column 'sip.sip.Application.Id' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause" error. But i have already included that column in the group by. So i'm not sure why it's still returning this error.
SQL Query
SELECT DISTINCT
a.[ApplicationId]
,a.[Id]
,a.[CompanyId]
,c.name AS CompanyName
,a.[CourseSIPRunId]
,ss.[AdminNo]
,count(CASE ss.StudentStatusCode WHEN 'ASG' THEN 1 ELSE 0 END) NoOfStudentsAllocated
,project.NoOfStudents
,project.[CourseCode]
,a.[AppStatusCode]
,appstat.AppStatusDescription
,project.[ProjectId]
,project.ProjectDescription
,a.CourseSIPRunId
,siprun.[AcadYear] + '-' + siprun.[Batch] As SIPBatch
,c.CompanyUEN
,c.PostalCode AS CompanyPostalCode
,course.CourseName
,project.[ResearchFlag] AS ResearchFlagString
,project.MPFlag AS MPFlagString
,project.[SIPType]
,project.ProjectDescription
,case when project.[SIPType]='OSIP' then 1 else 0 END IsOSIP
,case when project.[ResearchFlag] ='Y' then 1 else 0 END IsResearch
,case when project.[MPFlag] ='Y' then 1 else 0 END IsResearch
,project.MentorProjectLeader
,a.[SpecialRequirement]
,a.[MthlyAllowance]
,a.[OtherAllowance]
,a.[DaysPerWeek]
,a.[WeekdayHoursFrom]
,a.[WeekdayHoursTo]
,a.[SaturdayHoursFrom]
,a.[SaturdayHoursTo]
,a.[SundayHoursFrom]
,a.[SundayHoursTo]
,a.[ShiftWorkRequirement]
,a.[TPContactStaffEmailId]
,a.[SIPConfirmationDate]
,a.[SIPConfirmationBy]
,a.[Remarks]
,a.[SelfSource]
,a.[CreateSource]
,a.[CreatedDate]
,a.[SIPAllocationDate]
,a.[SIPAllocationBy]
,a.[SIPClosureDate]
,a.[SIPClosedBy]
,a.[LastUpdatedBy]
,a.[LastUpdatedDate]
,a.[AppStatusCode]
,a.[StatusReason]
,a.[OSIPCountryCode]
,a.[OSIPState]
,a.[OSIPCity]
,a.[OSIPDetails]
,a.[OverseasAssignment]
,a.[OverseasFrequency]
,a.[OverseasOtherCountry]
,a.[OverseasCountryCode]
,a.[OSIPOtherCountry]
,a.[OthersDetails]
,a.[OthersTPContactName]
,a.[OthersTPDiploma]
,a.[OthersEngagement]
,siprun.[StartDate]
,siprun.[EndDate]
,case when appotherinfo.AppOptionCode is null then 0 else 1 END IsInterviewRequired
,appotherinfo.AppOptionCode
FROM [sip].[sip].[Application] a
LEFT join [sip].[ApplicationStatus] appstat on a.AppStatusCode = appstat.AppStatusCode
LEFT join [sip].[ApplicationProject] project on a.ApplicationId = project.ApplicationId
LEFT JOIN [sip].[ApplicationProjectLO] lo on project.ProjectId = lo.ProjectId
LEFT JOIN [sip].[StudentSIP] ss on ss.ProjectId = lo.ProjectId
LEFT JOIN [sip].[ApplicationProjectSupervisor] s on s.ProjectId = project.ProjectId
LEFT JOIN [sip].[Company] c on c.CompanyId = a.CompanyId
LEFT JOIN [sip].[CourseSIPRun] siprun on a.CourseSIPRunId = siprun.CourseSIPRunId
LEFT JOIN [sip].[V_SIP_COURSE] course on project.CourseCode = course.COURSECODE
LEFT JOIN [sip].[ApplicationOtherInfo] appotherinfo on appotherinfo.ApplicationId = a.ApplicationId
group by a.[ApplicationId]
You include a.[ApplicationId] you don't include a.[Id] The error message is about the 2nd one.

Error cannot generate SQL for Custom SQL at BO

I'm using business object 4 and currently developing a report using custom SQL. Total object and data type selected using custom sql and object at webbi already the same. But when I try to validate webbi always sends error cannot generate sql.
How to fix this and what is the cause of this error?
My sql syntax is as follows:
select * from(
SELECT
DISTINCT
CASE WHEN TRIM(msv26A.PROJECT_NO) IS NULL THEN msvPRJ.PROJECT_NO ELSE msv26A.PROJECT_NO END,
msv660.PROJ_DESC,
msv26A.PO_NO,
msv200.SUPPLIER_NAME,
msv26A.SUPPLIER_NO,
msv260.EXT_INV_NO,
msv200.SUP_TYPEX1,
msv260.CURRENCY_TYPE,
msv000_DC0001.DSTRCT_CODE,
msv000_DC0001.DSTRCT_NAME,
msv260.PMT_STATUS,
msv260.DUE_DATE,
msv260.INV_DATE,
msv260.FOR_INV_ORIG,
msv260.LOC_INV_ORIG,
msv260.FOR_INV_AMD,
msv260.LOC_INV_AMD,
msv260.AMT_RETAINED,
msv260.PRESC_PMT_AMT,
msv260.PP_AMT_LOC,
msv260_1.AMT_PAID_FOR,
msv071.REF_CODE,
CASE WHEN EMV260_AGING_RETENTION.LOC_INV_RETENTION IS NULL THEN 0 ELSE EMV260_AGING_RETENTION.LOC_INV_RETENTION END,
CASE WHEN EMV260_AGING_RETENTION.FOR_INV_RETENTION IS NULL THEN 0 ELSE EMV260_AGING_RETENTION.FOR_INV_RETENTION END
FROM
msv200 RIGHT OUTER JOIN msv26A ON (msv26A.SUPPLIER_NO = msv200.SUPPLIER_NO)
INNER JOIN msv000_DC0001 ON (msv000_DC0001.DSTRCT_CODE = msv26A.DSTRCT_CODE)
INNER JOIN msv260 ON (msv26A.DSTRCT_CODE = msv260.DSTRCT_CODE AND msv26A.SUPPLIER_NO = msv260.SUPPLIER_NO AND msv26A.INV_NO = msv260.INV_NO)
LEFT OUTER JOIN msvPRJ ON (msvPRJ.DSTRCT_CODE = msv26A.DSTRCT_CODE AND TRIM(msvPRJ.PO_NO) = trim(msv26A.PO_NO))
LEFT OUTER JOIN msv660 ON (msv26A.DSTRCT_CODE = msv660.DSTRCT_CODE AND (CASE WHEN TRIM(msv26A.PROJECT_NO) IS NULL
THEN msvPRJ.PROJECT_NO ELSE msv26A.PROJECT_NO END) = msv660.PROJECT_NO)
LEFT OUTER JOIN msv260 msv260_1 ON (msv260_1.DSTRCT_CODE = msv260.DSTRCT_CODE and msv260_1.SUPPLIER_NO = msv260.SUPPLIER_NO and msv260_1.INV_NO = msv260.INV_NO)
LEFT OUTER JOIN msv071 ON (msv071.ENTITY_VALUE=msv260.SUPPLIER_NO AND msv071.ENTITY_TYPE='SUP')
LEFT OUTER JOIN (SELECT A.DSTRCT_CODE,
A.SUPPLIER_NO,
A.ORIG_INV_NO,
SUM(CASE WHEN A.LOC_INV_AMD <> 0
THEN A.LOC_INV_AMD ELSE A.LOC_INV_ORIG END) LOC_INV_RETENTION,
SUM(CASE WHEN A.FOR_INV_AMD <> 0
THEN A.FOR_INV_AMD ELSE A.FOR_INV_ORIG END) FOR_INV_RETENTION
FROM msv260 A
WHERE A.FULL_PER_LOADED <= #prompt('Enter Full Period(From):','A','260\Full Per Loaded',Mono,Free,Persistent,,User :3)
AND TRIM(A.PMT_STATUS) >= '30' AND TRIM(A.PMT_STATUS) <= '55'
GROUP BY
A.DSTRCT_CODE,
A.SUPPLIER_NO,
A.ORIG_INV_NO) EMV260_AGING_RETENTION
ON (msv260.DSTRCT_CODE = EMV260_AGING_RETENTION.DSTRCT_CODE
AND msv260.SUPPLIER_NO = EMV260_AGING_RETENTION.SUPPLIER_NO
AND msv260.INV_NO = EMV260_AGING_RETENTION.ORIG_INV_NO)
WHERE
msv26A.DSTRCT_CODE in #prompt('Enter value(s) for Dstrct Code:','A','msv26a\Dstrct Code',Multi,Free,Persistent,,User:5)
AND
TRIM(msv260.PMT_STATUS) >= '30' AND TRIM(msv260.PMT_STATUS) <= '55'
AND
(
( msv260.FULL_PER_LOADED <= #prompt('Enter Full Period(From):','A','260\Full Per Loaded',Mono,Free,Persistent,,User :3)
AND msv260.FULL_PER_PAID = '000000' )
OR
( msv260.FULL_PER_PAID > #prompt('Enter Full Period(To):','A','260\Full Per Paid',Mono,Free,Persistent,,User :4)
AND msv260.FULL_PER_LOADED <= #prompt('Enter Full Period(From):','A','260\Full Per Loaded',Mono,Free,Persistent,,User :3) )
)
AND msv260.CURRENCY_TYPE <> ' '
ORDER BY msv000_DC0001.DSTRCT_CODE, msv260.SUPPLIER_NO, msv200.SUP_TYPEX1, msv260.CURRENCY_TYPE)
WHERE (DSTRCT_CODE,SUPPLIER_NO,EXT_INV_NO) IN (SELECT
DISTINCT DSTRCT_CODE,SUPPLIER_NO,EXT_INV_NO FROM msv900
WHERE DSTRCT_CODE in #prompt('Enter value(s) for Dstrct Code:','A','msv900\Dstrct Code',Multi,Free,Persistent,,User:1)
AND FULL_PERIOD <= #prompt('Enter Full Period(From):','A','msv900\Full Period',Mono,Free,Persistent,,User :2)
AND ACCOUNT_CODE IN ('21101')
)
ORDER BY
PROJECT_NO,
SUPPLIER_NO

SQL joins returning multiple results

select
tmp.templatedesc Template
,sec.name Section
,q.questiontext Questions,
--,sum(case when q.responserequired = '0' then 1 else null end) as 'N/A'
--,sum(case when q.responserequired = '1' then 1 else null end) as Scored
--,count (case when (qr.weightedscore is not null and tmp.templatedesc = 'QA 30 Day Call Form' and
--sec.name = 'opening' and
--rv.reviewstatusid = 1 )then 1 else null end) as scored
----,(case when qr.weightedscore <> q.weight then rv.reviewid else null end) as fail
--count (case when qr.weightedscore is null then 1 else null end) NA,
--count (case when qr.weightedscore is not null then 1 else null end) scored,
sec.sequencenumber, q.questionnumber, qr.*
from
aqm.dbo.reviewtemplate tmp (nolock)
inner join aqm.dbo.section sec on sec.templateid =tmp.templateid
inner join aqm.dbo.sectionresult scr on scr.sectionid = sec.sectionid
inner join aqm.dbo.questionresult qr on qr.sectionresultid = scr.sectionresultid
inner join aqm.dbo.question q on q.questionid = qr.questionid
--inner join aqm.dbo.questiontype qt on qt.questiontypeid = q.questiontypeid
--left outer join aqm.dbo.questionoption qo on qo.questionid = q.questionid
inner join aqm.dbo.review rv on tmp.templateid = rv.templateid
inner join aqm.dbo.media md on md.mediaid = rv.mediaid
inner join aqm.dbo.iqmuser ut on md.userid = ut.userid
where
rv.reviewstatusid = 1 and
tmp.templatedesc = 'QA 30 Day Call Form'
and sec.name = 'opening' and
convert(varchar,dateadd(hh,-7,rv.reviewdate), 101) = '07/07/2014'
and ut.windowslogonaccount = 'name.name'
and q.questionnumber = 4
--group by
--tmp.templatedesc , sec.name, q.questiontext, sec.sequencenumber, q.questionnumber
order by
sec.sequencenumber, q.questionnumber
the questionresultid and sectionresultid are returning multiple values
how can i fix the joins so that it doesnt return multiple values?
i have it drilled down to a date and a person so that it should only return one row of results( but that obviously didnt work)
not sure what other data i can provide
update
i think it has to do with joins
inner join aqm.dbo.sectionresult scr on scr.sectionid = sec.sectionid
inner join aqm.dbo.questionresult qr on qr.sectionresultid = scr.sectionresultid
as those are the ones returning multiple results.
just dont know how to fix it
First, neither aqm.dbo.questiontype nor aqm.dbo.questionoption are used in your return fields or your where clause so get rid of them if they aren't required.
Second, you are OUTER JOINing on the aqm.dbo.review, but the reviewstatusid and reviewdate are required in the WHERE clause - so this should probably be an INNER JOIN.
Last, best way to debug issues like this is to comment out the COUNT statements and the GROUP BY clause - and see what raw data is being returned.