I have a query like this:
SELECT A, B, C,
CASE
WHEN 1 = (
SELECT COUNT(DISTINCT D)
FROM MyTable tbl2
WHERE tbl2.A = tbl.A AND tbl2.B = tbl.B and tbl2.C = tbl.C
)
THEN (
SELECT AVG(D)
FROM MyTable tbl3
WHERE tbl3.A = tbl.A AND tbl3.B = tbl.B and tbl3.C = tbl.C
)
ELSE SUM(D)
FROM MyTable tbl
GROUP BY A, B, C
Does anyone know of a better way to write this query?
What I’d really like, instead of re-querying the table twice, is to query each group of the group by in the select statement. Is that even possible?
I’m guessing it’s possible to do a JOIN of sorts, but if I would strongly prefer to query each group of original rows that are being aggregated together (to form the group).
I’m running on SQL Server 2005.
Thanks in advance for your help!
EDIT: 2011-11-09
In light of some of the questions, I think I didn’t explain my goals clearly enough. I hope this edit serves as a better example:
My question is this: When I do a group by, is there a way of querying the rows in the table that comprise of each group in the select statement? Is there some SQL keyword/function? Here’s what I mean:
Table:
| Code | Qty | ColumnA | ColumnB |
| A | 100 | 3 | 100 |
| A | 100 | 4 | 200 |
| A | 0 | 0 | 300 |
| B | 0 | 0 | 400 |
| B |100 | 1 | 500 |
SELECT Code, SUM(ColumnB),
(SELECT AVG(ColumnA) FROM Table WHERE Code = tbl.Code AND Qty <> 0) AS ColumnA
FROM Table tbl
GROUP BY Code
The output I’m looking for is:
| Code | ColumnA | ColumnB |
| A | 3.5 | 600 |
| B | 1 | 900 |
As you can see, I’d like to avoid that nested query by querying the 3 rows in the Table that group of A of comprised of. Do you know of a SQL keyword or function that gives me the original rows of each group? Or perhaps a better way to write the query?
I guess you simply want: