在SQL中,如果record为null,如何显示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)),但收到错误。
答案 0 :(得分:1)
使用+
时,两个参数必须属于同一类型。我无法从您的问题中了解car
是什么,但我认为它与0
不兼容。
在这些情况下最好使用CONCAT
。
CONCAT(car, IFNULL(car_orders, 0))
如果car_orders
是表格,则此处无效 - 您必须使用列,即car_orders.MyColumn
如何使用IFNULL
我认为你不能在这里得到一个null,鉴于你的查询,买你会像这样使用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;
答案 1 :(得分: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;
以上的关键是“LEFT OUTER JOIN”。如果您可以在自己的表中使用'sales1','sales2','sales3'值,那么这将更可取,而不是进行子选择。
希望这有帮助,
...约翰