简体   繁体   中英

I want to combine count of various SQL queries into one to show various columns

Select Count(1) as COUNT1 from
(
Select A,B from table1
union
Select A, B from table2
)
Select Count(1) as COUNT2 from 
(
Select C,D from table3
union
Select C,D from table4
)
Select Count(1) as COUNT3 from
(
Select E,F from table5
union
Select E,F from table6
);

I want to display a table showing COUNT1,COUNT2,COUNT3.

  SELECT a.COUNT1 ,
  b.COUNT2,
  c.COUNT3
FROM
  (SELECT COUNT(1) AS COUNT1
  FROM
    ( SELECT A,B FROM table1
    UNION
    SELECT A, B FROM table2
    )
  ) AS a,
  (SELECT COUNT(1) AS COUNT2
  FROM
    ( SELECT C,D FROM table3
    UNION
    SELECT C,D FROM table4
    )
  ) AS b,
  (SELECT COUNT(1) AS COUNT3
  FROM
    ( SELECT E,F FROM table5
    UNION
    SELECT E,F FROM table6
    )
  ) AS c;

Try this:

SELECT SUM(COUNT1) AS COUNT1, SUM(COUNT2) AS COUNT2, SUM(COUNT3) AS COUNT3
FROM
(
    Select Count(1) as COUNT1, 0 AS COUNT2, 0 AS COUNT3 from
    (
    Select A,B from table1
    union
    Select A, B from table2
    ) 
    UNION ALL
    Select 0 AS COUNT1, Count(1) as COUNT2, 0 AS COUNT3 from 
    (
    Select C,D from table3
    union 
    Select C,D from table4
    )
    UNION ALL
    Select 0 AS COUNT1, 0 AS COUNT2, Count(1) as COUNT3 from
    (
    Select E,F from table5
    union
    Select E,F from table6
    )
) AS a

Essentially, you are adding 1 row for every source table, while adding 0 values for the non-relevant counts. You finally perform a SUM over the resultset to end up with a single row containing the proper counts.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM