一尘不染

将多个结果合并为列而不是行

sql

我需要对数据库中的各个表执行多个计数
,我想将这些计数合并为一个结果。

考虑以下查询:

SELECT 100 As SomeCount
SELECT 200 As SomeOtherCount
SELECT 300 As YetAnotherCount

如果我使用组合它们UNION,则每个结果将在最终结果中排成一行:

SELECT 100 As SomeCount
UNION
SELECT 200 As SomeOtherCount
UNION
SELECT 300 As YetAnotherCount

输出:

> SomeCount
> --------- 
> 100 
> 200 
> 300

我想要的是

> SomeCount | SomeOtherCount | YetAnotherCount
> --------------------------------------------
>   100     |      200       |     300

我可以想到的“命名”结果的唯一其他方法是使用类似以下内容的方法:

SELECT 'SomeCount' As Name, 100 As Value
UNION ALL
SELECT 'SomeOtherCount', 200
UNION ALL
SELECT 'YetAnotherCount', 300

在这种情况下,结果如下所示:

>     Name          |      Value
> ---------------------------------
> 'SomeCount'       |       100
> 'SomeOtherCount'  |       200
> 'YetAnotherCount' |       300

有没有一种方法可以得到我想要的结果,还是最后一种方法呢?

我应该提到上面的查询非常简单,以解释核心问题。实际上,需要组合的两个查询可能看起来像这样:

查询1:

SELECT Count(Id) As UndeliveredSms
FROM
(
 SELECT Id
 FROM IncomingSms
 WHERE Id NOT IN (SELECT IncomingSmsId
                  FROM DeliveryAttempt
                  WHERE Status = 'Delivered' OR Status = 'FailedPermanently')
 )

查询2:

SELECT Count(Id) As UndeliveredEMail FROM
(
 SELECT Id
 FROM IncomingEMail
 WHERE Id NOT IN (SELECT IncomingEMailId
                  FROM DeliveryAttempt
                  WHERE Status = 'Delivered' OR Status = 'FailedPermanently')
)

将它们包装在另一条SELECT语句中不适用于SQlite。

在示例中使用最后一种方法确实可行,除非有坏主意,否则我可以使用该解决方案:

SELECT 'UndeliveredSms' As Name,  Count(Id) As Value
FROM
(
 SELECT Id
 FROM IncomingSms
 WHERE Id NOT IN (SELECT IncomingSmsId
                  FROM DeliveryAttempt
                  WHERE Status = 'Delivered' OR Status = 'FailedPermanently')
 )

UNION

SELECT 'UndeliveredEMail', Count(Id) FROM
(
 SELECT Id
 FROM IncomingEMail
 WHERE Id NOT IN (SELECT IncomingEMailId
                  FROM DeliveryAttempt
                  WHERE Status = 'Delivered' OR Status = 'FailedPermanently')
)

结果是这样的:

>     Name           |     Value
> ---------------------------------
> UndeliveredEMail   |       82
> UndeliveredSms     |       0

当然,实际上,还有很多事情要数


阅读 192

收藏
2021-05-16

共1个答案

一尘不染

您应该能够在查询之间使用CROSS JOIN:

SELECT *
FROM
(
  SELECT Count(Id) As UndeliveredSms
  FROM
  (
   SELECT Id
   FROM IncomingSms
   WHERE Id NOT IN (SELECT IncomingSmsId
                    FROM DeliveryAttempt
                    WHERE Status = 'Delivered' OR Status = 'FailedPermanently')
  )
)
CROSS JOIN
(
  SELECT Count(Id) As UndeliveredEMail FROM
  (
   SELECT Id
   FROM IncomingEMail
   WHERE Id NOT IN (SELECT IncomingEMailId
                    FROM DeliveryAttempt
                    WHERE Status = 'Delivered' OR Status = 'FailedPermanently')
  )
);

参见带有演示的SQL Fiddle

2021-05-16