1

Hello with this query I'm getting one result with four rows, how can I change it in order to get four named columns with their own result every one?

SELECT COUNT(*) FROM vehicles WHERE cus=1
UNION ALL
SELECT COUNT(*) FROM user WHERE cus=1
UNION ALL
SELECT COUNT(*) FROM vehicle_events WHERE cus=1
UNION ALL
SELECT COUNT(*) FROM vehicle_alerts WHERE cus=1

Thanks in advance.

0

2 Answers 2

5
SELECT a.ct veh_count, b.ct user_count, c.ct event_count, d.ct alert_count
FROM
( SELECT COUNT(*) ct FROM vehicles WHERE cus=1 ) a,
( SELECT COUNT(*) ct FROM user WHERE cus=1 ) b,
( SELECT COUNT(*) ct FROM vehicle_events WHERE cus=1 ) c,
( SELECT COUNT(*) ct FROM vehicle_alerts WHERE cus=1 ) d;
Sign up to request clarification or add additional context in comments.

Comments

2

UNION only adds rows; it has no effect on the columns.

Columns, which define the "shape" of the row tuples, must appear as selected columns1.

For example:

 SELECT
      (SELECT COUNT(*) FROM vehicles WHERE cus=1) as veh_count
     ,(SELECT COUNT(*) FROM users WHERE cus=1) as user_count
     ..

1 There are other constructs that can allow this, see crosstab for example - but the columns are fixed by the query command. It takes dynamic SQL to get a variable number of columns.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.