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
 Development Tools
 Other Development Tools
 [Access 2003 + SQL] Subqueries do not follow maste

Author  Topic 

iboumiza
Starting Member

9 Posts

Posted - 2011-11-19 : 23:04:13
Hi,

I have a query with 2 subqueries, and no error message is reported, but, my problem is that the 2 subqueries do not follow the GROUP BY rule and show the total instead of by vendor...

Code:

SELECT Table1.agents AS Vendor
, Count(Table1.carS) AS Car_Sold
, Sum(Table1.carP) AS Car_Price
, Count(Table1.busS) AS MortBus_Sold
, Sum(Table1.busP) AS busPRice
,
(
SELECT SUM(Table1.carS)
FROM Table1
WHERE (condition='Yes')
)
AS Car_bought_price,
(
SELECT COUNT(Table1.carB)
FROM Table1
WHERE (condition='Yes')
)
AS Good_condition
FROM Table1
WHERE (carS='Sold' Or busS=''Sold' ')
GROUP BY Table1.agents ;


Table:

Table1
Columns:
agents = John, Bill, Frank...
carS = Sold, Unsold
carP = Car selling price
busS = Sold, unsold
busP = Bus selling price
condition = Yes or No
carB = car buying price


How can I fix this, please?

Regards

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2011-11-20 : 01:45:36
the reason it doesnt work is you're not applying same conditions to subquery.
But actually you dont need subqueries at all. you can simply do like


SELECT Table1.agents AS Vendor
, Count(Table1.carS) AS Car_Sold
, Sum(Table1.carP) AS Car_Price
, Count(Table1.busS) AS MortBus_Sold
, Sum(Table1.busP) AS busPRice
, SUM(CASE WHEN condition='Yes' THEN Table1.carS ELSE 0 END) AS Car_bought_price
, COUNT(CASE WHEN condition='Yes' THEN Table1.carB ELSE NULL END) AS Good_condition
FROM Table1
WHERE (carS='Sold' Or busS=''Sold' ')
GROUP BY Table1.agents ;


------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

iboumiza
Starting Member

9 Posts

Posted - 2011-11-22 : 07:56:40
ok, I'll test it and get back to you :)
Go to Top of Page

iboumiza
Starting Member

9 Posts

Posted - 2011-11-22 : 07:56:40
ok, I'll test it and get back to you :)
Go to Top of Page
   

- Advertisement -