[英]How to combine two query's results into one row?
我有兩個查詢,每個查詢返回一個結果,即一個數字
Select Count(*) as StockCountA from Table_A where dept='AAA'
結果
StockCountA
550
。
Select Count(*) as StockCountB from Table_B where dept='BBB'
結果
StockCountB
450
我希望將兩個結果合並為一行記錄,即
| StockCountA | StockCountB
| 550 | 450
您可以使用:
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
說明:您可以在select語句中選擇單個值作為字段,因此可以編寫如下內容
select
x.*,
(select Value from Table_Y y) as ValueFromY
from
Table_X x
這僅適用於標量查詢 ,這意味着子查詢應具有恰好1列,最多1行。 如果行數為0,則ValueFromY將返回NULL
;如果行數超過1,則查詢將失敗。
select
的另一個功能(在SQL Server,MySQL和其他可能的版本中)是,您可以只選擇值,而無需完全指定表,如下所示:
Select
3.14 as MoreOrLessPI
您可以通過編寫如下查詢來將這兩個事實結合起來,將兩個計數結合為一個結果:
Select
(Select query that returns at most 1 row) as Result1,
(Select another query that returns at most 1 row) as Result2
這應該給您期望的結果:
SELECT * FROM(
(Select Count(*) as StockCountA from Table_A where dept='AAA') StockCountA ,
(Select Count(*) as StockCountB from Table_B where dept='BBB') StockCountB
);
試試下面的SQL:
select (Select Count(*) as StockCountA from Table_A where dept='AAA') StockCountA,
(Select Count(*) as StockCountB from Table_B where dept='BBB') StockCountB
希望這可以幫助 :)
雖然並非總是最佳做法,但可以進行交叉加入。
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'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.