两个表计入两个单独的列

Two tables count in to two seprate columns

我有两个 table 例如:

table1
---------------------
|id | name| isActive|
|---|-----|---------|
| 1 | dd  |    1    |
| 1 | cc  |    1    |
| 1 | zz  |    1    |
| 1 | yy  |    1    |
---------------------


table2
---------------------
|id | name| isActive|
|---|----|----------|
| 1 | ab  |    1    |
| 1 | cd  |    1    |
| 1 | ef  |    1    |
| 1 | gh  |    1    |
---------------------

要求是计算两个 table 的数量并将它们打印到两个单独的列中并在 birt 报告中将其打印到两个单独的列中 我已经尝试过这个

SELECT 
  COUNT(table2.`name`) Table1Count,
  table1.`isActive` Table1IsActive ,
  COUNT(table2.`name`) Table2Count,
  table2.`isActive` Table2IsActive 
FROM
  `table1`,
  `table2`

它的输出在两个单独的列中,但带有交叉连接

Table1Count  isActive  Table2Count  Table2IsActive  
-----------  --------  -----------  ----------------
  43316         0         3536                 1

我不能使用任何连接,因为这两个 table 都没有关系,而它的输出类似于我希望在单独的列中有两个 tables 计数的所需输出

通过尝试这个我得到了两个单独的行

SELECT 
  * 
FROM
   (SELECT 
   COUNT(*) Table1Count,
    table1.`isActive` Table1IsActive 
  FROM
    `table1` 
  UNION
  SELECT 
    COUNT(*) Table2Count,
    table2.`isActive` Table2IsActive 
  FROM
    `table2 `) AS a 

它的输出在两个单独的行中,而我的要求是单独的列

Table1Count   Table1IsActive 
------------   --------------
    442           0
     98           1

试试这个:

SELECT (SELECT COUNT(*) FROM `table1`) AS Table1Count, 
       (SELECT COUNT(*) FROM `table2`) AS Table2Count;

在您的 UNION 中,为另一个 table 中的列添加额外的列。然后使用 MAX()

组合它们
SELECT MAX(Table1Count) AS Table1Count, MAX(Table1IsActive) AS Table1IsActive,
       MAX(Table2Count) AS Table2Count, MAX(Table2IsActive) AS Table2IsActive
FROM (SELECT COUNT(*) Table1Count, table1.`isActive` Table1IsActive, 0 Table2Count, 0 Table2IsActive
      FROM `table1` 
      UNION
      SELECT 0 Table1Count, 0 Table1IsActive, COUNT(*) Table2Count, table2.`isActive` Table2IsActive 
      FROM `table2`) AS a 

UNION 将始终使用联合中第一个 select 的列名。由于两个查询 return 一行,您可以使用简单的笛卡尔积 (1 x 1 = 1) 来组合查询:

SELECT t1.Table1Count, t1.Table1IsActive, t2.Table2Count, t2.Table2IsActive
FROM
   (SELECT 
   COUNT(*) Table1Count,
   table1.isActive Table1IsActive 
  FROM
    table1
  GROUP BY table1.isActive
    ) as t1,
  (SELECT 
    COUNT(*) Table2Count,
    table2.isActive Table2IsActive 
  FROM
    table2 
  GROUP BY table2.isActive      
  ) as t2;

编辑

根据评论更新 - 我相信您所追求的是如下,即计算所有行并仅计算活动行(在一个查询中),然后在两个表中重复此操作,以投影单行结果:

SELECT 
       t1.Table1Count, t1.Table1Active, t2.Table1Count, t2.Table2Active
FROM
    (
       SELECT COUNT(t1.id) AS Table1Count, 
              SUM(CASE WHEN t1.IsActive = '1' THEN 1 ELSE 0 END) AS Table1Active 
       FROM Table1 t1
    ) t1,
    (
       SELECT COUNT(t2.id) AS Table1Count, 
              SUM(CASE WHEN t2.IsActive = '1' THEN 1 ELSE 0 END) AS Table2Active 
       FROM Table2 t2
    ) t2;

重要的是两个派生表(t1 和 t2)每个都展平为一行,否则笛卡尔积将重复行。