简体   繁体   English

SQl 将多个 CTE 的计数放入一张表中

[英]SQl get counts from multiple CTEs into one table

I have multiple CTEs which all come from the same table, "table1".我有多个 CTE,它们都来自同一个表“table1”。 And all they return is a count of the rows.他们返回的只是行数。 The differences between each CTE is the contents of the where statements as I want to compare the counts when I make these small changes.每个 CTE 之间的差异是 where 语句的内容,因为我想在进行这些小的更改时比较计数。 The code looks like:代码如下所示:

WITH cte1 AS(
SELECT COUNT(*)
FROM table1
WHERE....
), cte2 AS(
SELECT COUNT(*)
FROM table1
WHERE....
), cte3 AS(
SELECT COUNT(*)
FROM table 1
WHERE....
)

I want to get an output where I get all the counts from each CTE and just have them in one table like:我想得到一个 output ,我从每个 CTE 中获取所有计数,并将它们放在一个表中,例如:

cte1      cte2      cte3
1,564     3,567     2,861

As long as all of your CTEs return only 1 row you can just do the cartesian product of all of them (all in the from clause with no joins).只要您的所有 CTE 仅返回 1 行,您就可以对所有 CTE 进行笛卡尔积(全部在 from 子句中,没有连接)。 I believe you will need to give a column alias to your count(*) expression to include them in your CTE as well.我相信您需要为您的 count(*) 表达式提供一个列别名,以将它们也包含在您的 CTE 中。

WITH cte1 AS(
 SELECT COUNT(*) cnt 
 FROM table1
 WHERE....
), cte2 AS(
 SELECT COUNT(*) cnt
 FROM table1
 WHERE....
), cte3 AS(
 SELECT COUNT(*) cnt
 FROM table 1
 WHERE....
)
SELECT cte1.cnt AS cte1, cte2.cnt AS cte2, cte3.cnt AS cte3
FROM cte1, cte2, cte3

Also if you don't have any joins in your CTE you can potentially run the counts simultaneously by using sum case expressions which may increase performance.此外,如果您的 CTE 中没有任何联接,则可以使用 sum case 表达式同时运行计数,这可能会提高性能。

SELECT SUM(CASE WHEN /* where clause 1 */ THEN 1 ELSE 0 END) cte1,
       SUM(CASE WHEN /* where clause 2 */ THEN 1 ELSE 0 END) cte2,  
       SUM(CASE WHEN /* where clause 3 */ THEN 1 ELSE 0 END) cte3
FROM table1
SELECT
  (SELECT COUNT(*) FROM table1 WHERE....) as cte1,
  (SELECT COUNT(*) FROM table1 WHERE....) as cte2,
  (SELECT COUNT(*) FROM table1 WHERE....) as cte3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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