gpt4 book ai didi

sql - 将两个表合并为一个表,两个表都具有不同的 where 子句

转载 作者:行者123 更新时间:2023-12-04 01:26:56 24 4
gpt4 key购买 nike

我有如下两个 SQL 查询:

第一次查询

SELECT TC.TCName, 
sum(BS.BLDOS) as BLDOS,
sum(BS.CollectedAmount) as CollectedAmount,
(0.35*sum(BS.BLDOS)) as TargetAmount
FROM [Customer] C
INNER JOIN [dbo].[BillingStatus] BS ON BS.CustomerID = C.CustomerID
INNER JOIN [dbo].[TCDetails] TC ON TC.CustomerID = BS.CustomerID
WHERE TC.TCName in (Select distinct(TCName)
FROM [dbo].[TCDetails] )
GROUP BY TCName
order by [TCName] ASC

我得到一个结果:

   ||TCName ||  BLDOS  || CollectedAmount || TargetAmount||
| Aarti | 81234.2 | 1678.76 | 789065 |
| Dev | 181234.2| 678.76 | 2389065 |

第二个查询是:

SELECT COUNT(*) as count 
FROM [dbo].[TCDetails]
where TCName in (Select distinct(TCName) FROM [dbo].[TCDetails] )
AND CallDate is NOT NULL
GROUP BY TCName

我得到:

  ||count||
231
123

我想这样打印

   ||TCName ||  BLDOS  || CollectedAmount || TargetAmount|| count ||
| Aarti | 81234.2 | 1678.76 | 789065 | 231 |
| Dev | 181234.2| 678.76 | 2389065 | 123 |

我很困惑,因为两个查询都有不同的 wheres 子句

最佳答案

试试这个

SELECT  * FROM 
(
SELECT TC.TCName, sum(BS.BLDOS) as BLDOS, sum(BS.CollectedAmount) as CollectedAmount, (0.35*sum(BS.BLDOS)) as TargetAmount
FROM [Customer] C INNER JOIN
[dbo].[BillingStatus] BS ON BS.CustomerID = C.CustomerID INNER JOIN
[dbo].[TCDetails] TC ON TC.CustomerID = BS.CustomerID
WHERE TC.TCName in (Select distinct(TCName) FROM [dbo].[TCDetails] )
GROUP BY TCName order by [TCName] ASC
) S JOIN
(
SELECT TCName,COUNT(*) as count FROM [dbo].[TCDetails]
where TCName in (Select distinct(TCName) FROM [dbo].[TCDetails] )
AND CallDate is NOT NULL GROUP BY TCName
) T ON S.TCName=T.TCName;

运算符(operator):

+--------------------------------------------------------------+
|TCName | BLDOS | CollectedAmount | TargetAmount| count |
+--------------------------------------------------------------+
| Aarti | 81234.2 | 1678.76 | 789065 | 231 |
| Dev | 181234.2| 678.76 | 2389065 | 123 |
+--------------------------------------------------------------+

关于sql - 将两个表合并为一个表,两个表都具有不同的 where 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23286261/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com