tags:

views:

190

answers:

2

I am trying to update my table 1 with some field value from table 2 based on a condition. But am unable to get the proper query. Here's the condition:

I have a table 1 with date field which should be updated from table 2 date field. The condition is that the id of table 1 should be equal to id of table 2 (Table 2 has id of table 1 as FK). Another condition should be there is a varchar field in table 2 which should have specific value, say "Test". Wherever the value of field in table 2 is "Test" I want to update the date of with that record in table 1 date field. But there is another catch. It may be possible that more than 1 records for same id in table 2 can have value as "Test"

I was trying the query as:

UPDATE A
SET A.Date = Max(B.[Date])
FROM Table1 A
 INNER JOIN Table2 B ON A.ID = B.FK_ID
WHERE (B.Changed LIKE 'Test')
 AND A.Date IS NULL

But this is not working as sql does not allow Max in update when there is no group by. Please help. A bit urgent.

+1  A: 

You could always use subqueries:

UPDATE Table1 a SET
    [Date] = (SELECT MAX([Date]) FROM Table2 b WHERE a.ID = b.FK_ID AND b.Changed LIKE 'Test')
WHERE [Date] IS NULL
David Hedlund
looks about right, but why use LIKE instead of equals ?
Steve De Caux
my first impulse was to edit it to equals, but then i figured `Test` was so obviously a made up example value, so i guess it could be taken as read that it something else will actually go there in the live implementation of this, and from there, i just assumed that Ted knew about the differences between `LIKE` and `=` and decided not to pick on that, since it was rather peripherous to the question =)
David Hedlund
Cool bananas, wanted to make sure I hadn't missed out on a random syntax change
Steve De Caux
+1  A: 

You need to create another inner join where the ID's of Table1 are coupled with the maximum dates of Table2 like so:

UPDATE    Table1
SET       Date = BDate.MaxDate
FROM      Table1 A
          INNER JOIN Table2 B ON A.ID = b.FK_ID
          INNER JOIN (
              SELECT    A.ID, [MaxDate] = MAX(B.Date)
              FROM      Table1 A
                        INNER JOIN Table2 B ON A.ID = b.FK_ID
              GROUP BY  A.ID
          ) BDate ON BDate.ID = A.ID
WHERE     B.Changed LIKE 'Test'
          A.Date IS NULL
Lieven