I have the following query which gives me the error "Only one expression can be specified in the select list when the subquery is not introduced with EXISTS". I am unable to figure what's technically wrong with this.
select clinicid,
DATEPART(YEAR,CONVERT(date,PackagePatients.SaleDate )) as YEAR,
DATEPART(MONTH,CONVERT(date,PackagePatients.SaleDate )) as MONTH,
REPLACE(RIGHT(CONVERT(VARCHAR(9),PackagePatients.SaleDate, 6), 6), ' ', '-') AS SalMonYY,
(select rpTotal.clinicid,SUM(rpTotal.rpPackage) as rpPackage from
(
select clinicid, count(1) as rpPackage
from PackagePatients
WHERE PackagePatients.clinicid = clinicid
AND convert(date,patientdate) < convert(date,saledate)
group by clinicid
union all
select s.homeClinicId as clinicid,COUNT(1) as rpPackage
from subscriptionHistory s
join patients p on s.ptientId = p.id
join products pl on s.productId = pl.id
WHERE s.HomeClinicId = clinicid
and pl.expDuration > 1
group by s.homeClinicId) rpTotal group by rpTotal.clinicid) AS rpPackagesSold
from PackagePatients
group by clinicid,
DATEPART(YEAR,CONVERT(date,PackagePatients.SaleDate )),
DATEPART(MONTH,CONVERT(date,PackagePatients.SaleDate )),
REPLACE(RIGHT(CONVERT(VARCHAR(9),PackagePatients.SaleDate, 6), 6), ' ', '-')
(select rpTotal.clinicid,SUM(rpTotal.rpPackage)has two columns. It is in a context where a scalar subquery is allowed, but a scalar subquery can only return one column from at most one row.