Solved

SQL Update with nested select and aggregate function

Posted on 2008-06-12
3
4,170 Views
Last Modified: 2008-06-13
I'm trying to update one column of a table with the following query:

UPDATE Utable
Set Amt =
   (SELECT
        Sum(Amt)
    FROM Ptable
    WHERE ID IN
        (SELECT ID FROM UTable)
    GROUP BY
        ID,
        Col1,
        Col2,
        Col3
    )

I'd like the sum of AMT from Ptable to be placed in Utable  but I keep getting various error messages -- can I do this in one update statement -- How would I do it?
   
0
Comment
Question by:dkcoop03
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
3 Comments
 
LVL 8

Accepted Solution

by:
i2mental earned 250 total points
ID: 21772287
I'm going to assume that Ptable has multiple rows to each Utable ID.

UPDATE Utable
set utable.amt = (select sum(amt) from Ptable where ptable.id = utable.id)
0
 

Author Comment

by:dkcoop03
ID: 21778165
I have one question regarding this solution -- why doesn't  the nested select with the Sum(amt) require a group by clause?
0
 

Expert Comment

by:crobledo
ID: 31817188
MS SQL:

Can I work a query as such

Max(Count(field1), Count(field2), Count(field3))  AS thisField

In other words can I easily nest aggregate function
0

Featured Post

Comprehensive Backup Solutions for Microsoft

Acronis protects the complete Microsoft technology stack: Windows Server, Windows PC, laptop and Surface data; Microsoft business applications; Microsoft Hyper-V; Azure VMs; Microsoft Windows Server 2016; Microsoft Exchange 2016 and SQL Server 2016.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
JSON is being used more and more, besides XML, and you surely wanted to parse the data out into SQL instead of doing it in some Javascript. The below function in SQL Server can do the job for you, returning a quick table with the parsed data.
This video shows how to set up a shell script to accept a positional parameter when called, pass that to a SQL script, accept the output from the statement back and then manipulate it in the Shell.
Via a live example, show how to shrink a transaction log file down to a reasonable size.

691 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question