1

在 SQL 中,如果记录为空,如何显示 0?

select sales_id, totalbuy, totalsell, totalbuy + totalsell as total from
(select sales_id, SUM(CASE WHEN side= 'buy' THEN 1 ELSE 0 END) AS totalbuy, 
SUM(CASE WHEN side= 'sell' THEN 1 ELSE 0 END) AS totalsell 
from car_orders 
where sales_id in ('sales1', 'sales2', 'sales3', 'sales4')only
GROUP BY sales_id)q
order by total desc
limit 0, 10;

car_orders我尝试插入 *(car_orders+ISNULL(car_orders,0)) 但收到错误后。

4

2 回答 2

1

使用 时+,两个参数必须是同一类型。我无法从您的问题中看出是什么car,但我认为它与0.

最好CONCAT在这些情况下使用。

CONCAT(car, IFNULL(car_orders, 0))

如果car_orders是表,则此处无效-您必须使用列,即car_orders.MyColumn

如何使用 IFNULL

我不认为你可以在这里得到一个空值,给定你的查询,买你会像这样使用 IFNULL :

SELECT 
    sales_id,
    IFNULL(totalbuy, 0),
    IFNULL(totalsell, 0),
    IFNULL(totalbuy, 0) + IFNULL(totalsell, 0) as total
FROM
(
    SELECT
        sales_id,
        SUM(CASE WHEN side = 'buy' THEN 1 ELSE 0 END) AS totalbuy, 
        SUM(CASE WHEN side = 'sell' THEN 1 ELSE 0 END) AS totalsell 
    FROM
        car_orders 
    WHERE
        sales_id in ('sales1', 'sales2', 'sales3', 'sales4')
    GROUP BY
       sales_id
) q
ORDER BY total DESC
LIMIT 0, 10;
于 2012-11-01T17:08:57.323 回答
1

根据 Sohnee 的回答构建,这是我认为您想要使用的 SQL:

SELECT 
    sales_id,
    IFNULL(totalbuy, 0),
    IFNULL(totalsell, 0),
    IFNULL(totalbuy, 0) + IFNULL(totalsell, 0) as total
FROM
(
    SELECT
        sid as sales_id,
        SUM(CASE WHEN side = 'buy' THEN 1 ELSE 0 END) AS totalbuy, 
        SUM(CASE WHEN side = 'sell' THEN 1 ELSE 0 END) AS totalsell 
    FROM 
        ( SELECT 'sales1' as sid UNION SELECT 'sales2' UNION SELECT 'sales3' UNION SELECT 'sales4' ) mysalesids
    LEFT OUTER JOIN car_orders
      ON sales_id = sid
    GROUP BY
       sales_id
) q
ORDER BY total DESC
LIMIT 0, 10;

The key to the above is the "LEFT OUTER JOIN". If you can have the 'sales1', 'sales2', 'sales3' values in their own table, that would be preferable rather than having a sub-select.

Hope this helps,

john...

于 2012-11-01T17:32:39.727 回答