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.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 How to make multi conditional QUERY?

Author  Topic 

machine
Starting Member

1 Post

Posted - 2014-08-21 : 16:03:53
SELECT
`loanac`.`id`,
`loanac`.`name`,
`loanac`.`lacc`,
SUM(`loantrans`.`in`) as totalin,
SUM(`loantrans`.`out`) as totalout

FROM loanac, loantrans
WHERE `loanac`.`lacc`=`loantrans`.`account`
GROUP BY `loanac`.`lacc`

Here is my query above which is working fine to show all accounts, BUT I need to find accounts where SUM(out) > SUM (in) instead of all accounts

I've tried to add condition using AND but its showing error, can anyone help?

Here is the db link in case if u want to take a look
https://www.dropbox.com/sh/o0ro7r23ztnpfky/AABrfLYUB5DUk-FRvPegHZF_a

Machine

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2014-08-21 : 16:13:56
[code]
;
WITH CTE (id, name, lacc, totalin, totalout)
AS
(
SELECT
loanac.id,
loanac.name,
loanac.lacc,
SUM(loantrans.in) as totalin,
SUM(loantrans.out) as totalout
FROM loanac
JOIN loantrans ON loanac.lacc=loantrans.account
GROUP BY loanac.lacc
)
SELECT *
FROM CTE
WHERE totalout > totalin
[/code]

Tara Kizer
SQL Server MVP since 2007
http://weblogs.sqlteam.com/tarad/
Go to Top of Page

bitsmed
Aged Yak Warrior

545 Posts

Posted - 2014-08-21 : 16:55:15
Alternative:

SELECT
`loanac`.`id`,
`loanac`.`name`,
`loanac`.`lacc`,
SUM(`loantrans`.`in`) as totalin,
SUM(`loantrans`.`out`) as totalout

FROM loanac
INNER JOIN loantrans ON `loanac`.`lacc`=`loantrans`.`account`
GROUP BY `loanac`.`lacc`
HAVING SUM(`loantrans`.`out`)>SUM(`loantrans`.`out`)
Go to Top of Page

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2014-08-21 : 17:04:35
Oh yes HAVING!

Tara Kizer
SQL Server MVP since 2007
http://weblogs.sqlteam.com/tarad/
Go to Top of Page

bitsmed
Aged Yak Warrior

545 Posts

Posted - 2014-08-21 : 17:14:27
Correction to my last post. Out should be greater than In, and not like I wrote Out greater than Out, which is rubbish.

quote:
Originally posted by bitsmed

Alternative:

SELECT
`loanac`.`id`,
`loanac`.`name`,
`loanac`.`lacc`,
SUM(`loantrans`.`in`) as totalin,
SUM(`loantrans`.`out`) as totalout

FROM loanac
INNER JOIN loantrans ON `loanac`.`lacc`=`loantrans`.`account`
GROUP BY `loanac`.`lacc`
HAVING SUM(`loantrans`.`out`)>SUM(`loantrans`.`outin`)


Go to Top of Page
   

- Advertisement -