mysql:用标题显示多个结果

时间:2015-04-12 23:18:52

标签: mysql

我是一个完整的新手,请原谅我。

我试图让结果显示2个或更多不同的标题。

SELECT sum(fare) AS totalfare, count(*) AS fare10 
where fare>10
FROM tbl

我正在尝试仅将WHERE语句应用于count,而不是sum,并将结果显示为“totalfare”“{{1 }}“

fare10

我已经尝试过这种方式,但结果网格会将1个标题下的答案吐出作为总票价。是否可以将其显示为SELECT sum(fare) AS totalfare FROM tbl union SELECT count(*) AS watever FROM tbl where fare > 10

2 个答案:

答案 0 :(得分:1)

最后你解释了你的问题。只有当表(结果集)具有相同的字段时,才能执行UNION。这就是你需要的。上面的查询直接从两个子查询创建的派生表中选择。

SELECT 
    *
FROM
    (SELECT 
        SUM(fare) AS totalfare
    FROM
        tbl) a,
    (SELECT 
        COUNT(*) AS watever
    FROM
        tbl
    WHERE
        fare > 10) b

您将获得一行结果

[ totalfare | watever ]
   number      number

答案 1 :(得分:0)

您想要条件聚合:

SELECT sum(fare) AS totalfare,
       sum(case when fare > 10 then 1 else 0 end) as fare10
FROM tbl;

在MySQL中,您还可以将其缩短为:

SELECT sum(fare) AS totalfare,
       sum(fare > 10) as fare10
FROM tbl;