getting "No column was specified for column 2 of 'd'" in sql server cte?
I had a similar query and a similar issue.
SELECT
*
FROM
Users ru
LEFT OUTER JOIN
(
SELECT ru1.UserID, COUNT(*)
FROM Referral r
LEFT OUTER JOIN Users ru1 ON r.ReferredUserId = ru1.UserID
GROUP BY ru1.UserID
) ReferralTotalCount ON ru.UserID = ReferralTotalCount.UserID
I found that SQL Server was choking on the COUNT(*)
column, and was giving me the error No column was specified for column 2.
Putting an alias on the COUNT(*)
column fixed the issue.
SELECT
*
FROM
Users ru
LEFT OUTER JOIN
(
SELECT ru1.UserID, COUNT(*) AS -->MyCount<--
FROM Referral r
LEFT OUTER JOIN Users ru1 ON r.ReferredUserId = ru1.UserID
GROUP BY ru1.UserID
) ReferralTotalCount ON ru.UserID = ReferralTotalCount.UserID
[edit]
I tried to rewrite your query, but even yours will work once you associate aliases to the aggregate columns in the query that defines 'd'.
I think you are looking for the following:
First one:
select
c.duration,
c.totalbookings,
d.bkdqty
from
(select
month(bookingdate) as duration,
count(*) as totalbookings
from
entbookings
group by month(bookingdate)
) AS c
inner join
(SELECT
duration,
sum(totalitems) 'bkdqty'
FROM
[DrySoftBranch].[dbo].[mnthItemWiseTotalQty] ('1') AS BkdQty
group by duration
) AS d
on c.duration = d.duration
Second one:
select
c.duration,
c.totalbookings,
d.bkdqty
from
(select
month(bookingdate) as duration,
count(*) as totalbookings
from
entbookings
group by month(bookingdate)
) AS c
inner join
(select
month(clothdeliverydate) 'clothdeliverydatemonth',
SUM(CONVERT(INT, deliveredqty)) 'bkdqty'
FROM
barcodetable
where
month(clothdeliverydate) is not null
group by month(clothdeliverydate)
) AS d
on c.duration = d.duration
You just need to provide an alias for your aggregate columns in the CTE
d as (SELECT
duration,
sum(totalitems) as sumtotalitems
FROM
[DrySoftBranch].[dbo].[mnthItemWiseTotalQty] ('1') AS BkdQty
group by duration
)