SQL 如何将两个查询的结果合并为一行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27238170/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 03:00:47  来源:igfitidea点击:

How to combine two query's results into one row?

sqlsql-server

提问by Rosebud

I have two queries that return one result each i.e one number

我有两个查询,每个查询返回一个结果,即一个数字

Select Count(*) as StockCountA from Table_A where dept='AAA'

Results

结果

StockCountA 
550

.

.

Select Count(*) as StockCountB from Table_B where dept='BBB'

Results

结果

StockCountB 
450

I wish to join the two results into one row record i.e

我希望将两个结果合并为一行记录,即

| StockCountA | StockCountB    
| 550         | 450

回答by GolezTrol

You can use:

您可以使用:

select
(Select Count(*) as StockCountA from Table_A where dept='AAA') as StockCountA,
(Select Count(*) as StockCountB from Table_B where dept='BBB') as StockCountB

Explanation: you can select single value as a field in a select statement, so you could write something like

说明:您可以在 select 语句中选择单个值作为字段,因此您可以编写类似

select
  x.*,
  (select Value from Table_Y y) as ValueFromY
from
  Table_X x

This will work only with scalarqueries, meaning that the sub-query should have exactly 1 column, and at most 1 row. With 0 rows ValueFromY will return NULLand with more than 1 row, the query will fail.

这仅适用于标量查询,这意味着子查询应该正好有 1 列,最多 1 行。ValueFromY 将返回 0 行NULL,超过 1 行,查询将失败。

An additional feature of select(in SQL Server, MySQL and probably others) is that you can select just values without specifying a table at all, like this:

select(在 SQL Server、MySQL 和其他可能的情况下)的附加功能是您可以只选择值而不指定表,如下所示:

Select
  3.14 as MoreOrLessPI

You can combine both those facts to combine the two counts into a single result, by writing a query that looks like:

通过编写如下所示的查询,您可以将这两个事实结合起来,将这两个计数合并为一个结果:

Select
  (Select query that returns at most 1 row) as Result1,
  (Select another query that returns at most 1 row) as Result2

回答by Darshan Mehta

This should give you the desired result:

这应该会给你想要的结果:

SELECT * FROM(
(Select Count(*) as StockCountA from Table_A where dept='AAA') StockCountA ,
(Select Count(*) as StockCountB from Table_B where dept='BBB') StockCountB
);

回答by Leptonator

While not always the best practice, it is possible to do a CROSS JOIN..

虽然并不总是最佳实践,但可以进行 CROSS JOIN..

SELECT
COUNT(Table_A.SOME_COLUMN) as StockCountA
,COUNT(Table_B.SOME_COLUMN) as StockCountB
FROM Table_A, Table_B WHERE Table_A.dept='AAA' AND Table_B.dept='BBB'

回答by Hemant Patel

Try below SQL :

试试下面的 SQL :

select (Select Count(*) as StockCountA from Table_A where dept='AAA')  StockCountA, 
       (Select Count(*) as StockCountB from Table_B where dept='BBB')  StockCountB

Hope This Helps :)

希望这可以帮助 :)