tags:

views:

21

answers:

3

Here is sample query

SELECT 
    name, 
    sum(SELECT id FROM mytable WHERE cond='1' and cond2='2') as mysum1, 
    sum(SELECT id FROM mytable WHERE cond3='3' and cond4='4') as mysql2 
FROM 
    mytable 
WHERE 
    userid='1' and status='1';

Obviously this does not work but I think you can now understand what I mean. How to retrieve records in this manner.

A: 

You need to calculate sums inside subqueries:

SELECT 
    name, 
    (SELECT sum(numbers) FROM mytable WHERE cond='1' and cond2='2') as mysum1, 
    (SELECT sum(numbers) FROM mytable WHERE cond3='3' and cond4='4') as mysym2
FROM 
    mytable 
WHERE 
    userid='1' and status='1';
Māris Kiseļovs
+1  A: 

Try this

SELECT 
    name, 
    (SELECT SUM(id) FROM mytable WHERE cond='1' and cond2='2') as mysum1, 
    (SELECT SUM(id) FROM mytable WHERE cond3='3' and cond4='4') as mysql2 
FROM 
    mytable 
WHERE 
    userid='1' and status='1';
Gunjan
A: 

If you want to get a count of rows matching these conditions, use this query:

SELECT 
    name, 
    SUM(cond='1' AND cond2='2') AS mysum1,
    SUM(cond3='3' AND cond4='4') AS mysum2
FROM mytable 
WHERE 
    userid='1' AND 
    status='1';
Naktibalda