Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
Mikael
Starting Member
1 Post |
Posted - 2012-09-05 : 13:23:44
|
| Hi I have two tablesTransactionsID | Amount | year1 | 100 | 20121 | -100 | 20112 | 100 | 20123 | 100 | 20123 | -50 | 2011InvoiceID | Number | year1 | ABC123 | 20112 | DEF456 | 20123 | GHI789 | 2011I need to write a query that looks through the transactionstable and shows all ID whose total amount isnt zero. ID in this case isnt a key and can be reused for all years. That's why in my query I want to display the invoice that correspond to the ID and the smallest year for that ID in transactions. This is what I've tried:SELECT ID, sum(amount) FROM transactionsLEFT JOINON transactions.id = invoice.idAND transactions.year = invoice.yearGROUP by transactions.idHAVING (sum(transactions.id)<>0)In this case I get this result:1 100 NULL 1 -100 ABC1232 100 DEF4563 100 NULL3 -50 GHI789This is what I want:2 100 DEF45693 50 GHI789Anyone got any ideas? |
|
|
sunitabeck
Master Smack Fu Yak Hacker
5155 Posts |
Posted - 2012-09-05 : 14:25:34
|
May be more like this?SELECT t.Id, SUM(t.AMOUNT), i.NumberFROM Transactions t INNER JOIN Invoice i ON i.ID = t.IDGROUP BY t.Id, i.NumberHAVING SUM(t.AMOUNT) <> 0; |
 |
|
|
|
|
|