multiple fields in aggregate


I need to move data from tblResults into tblReports.

tblResults looks like this:

ID  Method  Value
1       12        13.2
2       12        12.5
3       13        27.4
4       13        13.1

tblResults needs to be:
ID      NO3N     P
1         25.7     40.5

My "SELECT Sum(Value) AS NO3N WHERE Method = 12" picks up one value but bombs when I try to nest another.

Can you give me a model?

Glen GibbOwnerAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

what do you want to calculate in P?

is it is sum(Value) where Method=13 ?
Here's one way:

SELECT     a.NO3N, b.P
FROM         (SELECT     SUM([value]) AS NO3N
                       FROM          tblResults
                       WHERE      method = 12) a CROSS JOIN
                          (SELECT     SUM([value]) AS P
                            FROM          tblResults
                            WHERE      method = 13) b

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Glen GibbOwnerAuthor Commented:

In a word, yes.  I actually am trying to obtain a resultset of 13 different chemical tests.  I have only supplied two, thinking that if someone can help me model the second field, I can add the others from the example.


This looks like the ticket, but can you explain the lower case a.NO3N, b.P to me?  Do these denominate a column?


Sure.  I'm using the sub-queries in a way that's called Derived Tables, where I'm treating the results as separate tables and joining them.  Because the results are actually coming from the same table, I'm giving each one a name, or alias (a for the first, b for the second), and referring to each table by that.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server

From novice to tech pro — start learning today.