1

我有一个销售 ID 列表,后跟他们的总销售额和购买量。我现在想总结总销售额和购买量。我试图插入 sum totalbuy 和 totalsell 作为总数。但这并没有奏效。

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 like '%%' 
GROUP BY sales_id
4

3 回答 3

0

where如果您想要与该子句匹配的所有 salesid 的总数,请删除group by

select 
   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 like '%%' 
于 2012-11-01T16:07:57.220 回答
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 like '%%' 
   GROUP BY sales_id)q

或者如果边只能是“买”或“卖”

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,
  COUNT(*) as total
FROM car_orders 
WHERE sales_id like '%%' 
GROUP BY sales_id
于 2012-11-01T15:57:19.163 回答
0
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,
   SUM(1) as totalbuyplussell 
from car_orders 
where sales_id like '%%' 
GROUP BY sales_id

假设方 = 买入或卖出。

于 2012-11-01T15:58:04.187 回答