开发者

How to select different columns from database each giving the sum(or similar) of another query result?

Here is sample query

SELECT 
    name, 
    sum(SELECT id FROM mytable WHERE开发者_JAVA百科 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.


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';


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';


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';
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜