all groups > sql server programming > june 2007 >
You're in the

sql server programming

group:

Update with subquery


Update with subquery Charlie
6/10/2007 9:08:00 PM
sql server programming:
I am trying to run an update to a table that requies a count from another
table and want the update to be where the Year & Month are equal to each
other. I am trying to work with a poorly set up table structure and am
having a hard time trying to figure out how to get an update to work form a
subquery (not good with subqueries, still new to this)

Table Structure to be updated:

tblQuestions
(
Year int
,Month int
,InfoReceived int
)

Here is an example of the "subquery":

SELECT COUNT(tblCustomers.CustomerID)
FROM Table1 INNER JOIN
tblQuestions ON tblCustomers.Customer.ID = tblQuestions.ID
WHERE (tblQuestions.InfoReceived = 1)
GROUP BY DATEPART(Year, tbl.Customers.ADDDate), DATEPART(Month,
tbl.Customers.ADDDate.EffDate))

I want to update tblQuestions with the Count from the above query, but it
needs to update where the DATEPART(Year, tbl.Customers.ADDDate) = Year, AND
DATEPART(Month, tbl.Customers.ADDDate.EffDate) = Month

How do I do this? I have tried several things and am just not having a luck
what so ever. (two days now!) And just can not find an example of doing
what I want to do. Is this not possible?

Any help is so greatly appreciated.


Re: Update with subquery M A Srinivas
6/10/2007 9:33:48 PM
[quoted text, click to view]

You are almost there
UPDATE A SET
InfoReceived = B.InfoReceived
FROM tblQuestions A,
( SELECT COUNT(tblCustomers.CustomerID) as
InfoReceived ,DATEPART(Year, tbl.Customers.ADDDate) as CustYear,
DATEPART(Month,
tbl.Customers.ADDDate.EffDate) as CustMonth
FROM Table1 INNER JOIN
tblQuestions ON tblCustomers.Customer.ID = tblQuestions.ID
WHERE (tblQuestions.InfoReceived = 1)
GROUP BY DATEPART(Year, tbl.Customers.ADDDate),
DATEPART(Month,
tbl.Customers.ADDDate.EffDate) ) AS B
A.[Year] = B.CustYear
AND A.[Month] = B.CustMonth

I suggest avoid naming your columns Year, Month as these are SQL
Server Keywords


Re: Update with subquery Charlie
6/10/2007 9:49:02 PM
THANK YOU SO MUCH! I see where I was going wrong in my earlier attempts now
too. Thanks for the tip on the names: Month & Year, those aren't the full
names being used, I was just trying to keep things short :-)

[quoted text, click to view]
AddThis Social Bookmark Button