0

I would like to calculate the rows in the table with each other condition. I have this in some way, but it does not work.

$sql = "SELECT
 (SELECT COUNT(name) FROM orders) as total,
  UNION ALL
 (SELECT COUNT(name) FROM orders  WHERE status='1') as ok,
  UNION ALL
 (SELECT COUNT(name) FROM orders  WHERE status='2') as ko";
Pito
  • 9
  • 2

2 Answers2

0

Use conditional aggregation:

select count(*) as total, sum(status = 1) as ok, sum(status = 2) as ko
from orders;

Note: This assumes that status is really stored as a number. Don't use single quotes for numeric constants (do use them when you really intend a string).

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0

You can count data of more than one tableusing simple query

$sql = "SELECT COUNT(name) AS `total`, (SELECT COUNT(name) FROM orders  WHERE status='1') as `second`, (SELECT COUNT(name) FROM orders  WHERE status='2') as `third` FROM orders";

For more information please check here

Jenish
  • 535
  • 4
  • 16