Skip to content
Advertisement

How to get calculated data from one column in database

im new in sql. I cannot get data with format what i want in one step. Now i’m using more sql commands. I want to get all data in one command because i cant to connect them in subquery with group by. Somebodys can help me?

example of Table i have:

id order_id order_status
1 1 0
2 1 0
3 1 0
4 1 1
5 1 1
6 2 0
7 2 0
8 2 1

Table i want to have after sql query:

order_id count of progress(%)
1 2 5 40
2 1 3 33

queries i use:

SELECT order_id, COUNT(status) as count
FROM `orders`
WHERE status = 1
GROUP by order_id;
SELECT order_id, COUNT(status) as of
FROM `orders`
GROUP by order_id;
SELECT order_id,
       CAST((SELECT COUNT(status) FROM `orders` WHERE status = 1) /
            (SELECT COUNT(status) FROM `orders`) *100 as int) AS progress FROM orders
group by order_id;

but last working properly only if i use where to single order id.

I want to make this data in one sql query to format i showed up.

Thanks a lot guys!

Advertisement

Answer

you need to use multiple subqueries here’s a query that I used and worked on your example on the onecompiler.com website

-- create
CREATE TABLE EMPLOYEE (
  order_id INTEGER,
  order_status INTEGER
);

-- insert
INSERT INTO EMPLOYEE VALUES (1,0 );
INSERT INTO EMPLOYEE VALUES (1, 0);
INSERT INTO EMPLOYEE VALUES (1, 0);


INSERT INTO EMPLOYEE VALUES (1, 1);
INSERT INTO EMPLOYEE VALUES (1,1 );


INSERT INTO EMPLOYEE VALUES (2, 0);
INSERT INTO EMPLOYEE VALUES (2, 0);
INSERT INTO EMPLOYEE VALUES (2, 1);

select *
from EMPLOYEE;

SELECT order_id, count, off , count/off
from(
    select distinct order_id as order_id, 
    (select count(order_id) from EMPLOYEE C WHERE A.order_id=C.order_id  AND order_status =1)  as 'count',
    (select count(order_id) from EMPLOYEE B WHERE A.order_id=B.order_id )  as 'off'
    FROM EMPLOYEE A
    ) AA
    ;
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement