SQL查询:如何将计数函数结果组合到选择查询中?

时间:2009-04-09 20:58:00

标签: sql

select distinct Franchise.FranchiseName, Franchise.Initials, Franchise.StoreNo, AccountCancellation_Process.Store_Num 
FROM FranchiseData
INNER JOIN AccountCancellation_Process
on FranchiseData.StoreNo = AccountCancellation_Process.Store_Num

select count(*) from AccountCancellation_Process where Store_Num = '1234' 
select count(*) from AccountCancellation_Process where Store_Num = '1234' and Progress is not null

我想将AccountCancellation_Process中的count(*)组合到上面的内连接语句中,这样查询将从Franchise表中获得FranchiseName,Initials,StoreNo和来自AccountCancellation_Process的Store_Num的结果,其中包含总记录和总记录进度列不为空。

如何将查询结果与计数函数结果相结合?

感谢。

2 个答案:

答案 0 :(得分:2)

像这样我认为是你想要的。 我创建了两个表值相关子查询,以根据内连接表中存储的数字获取数据。然后我根据商店号码加入他们。这样,独特的将起作用。但是,您也可以使用仅相关的子查询来执行选择部分中的计数。我担心明显可能不起作用。

SELECT DISTINCT Franchise.FranchiseName, Franchise.Initials, Franchise.StoreNo, acp.Store_Num, total_count.Total_Count, progress_count.Progress_Count
FROM FranchiseData
     INNER JOIN AccountCancellation_Process AS acp ON (FranchiseData.StoreNo = acp.Store_Num)
     INNER JOIN (SELECT Store_Num, COUNT(*) AS Total_Count FROM AccountCancellation_Process WHERE Store_Num = acp.Store_Num) AS total_count ON (acp.Store_Num = total_count.Store_Num)
     INNER JOIN (SELECT Store_Num, COUNT(*) AS Progress_Count FROM AccountCancellation_Process WHERE Store_Num = acp.Store_Num AND Progress IS NOT NULL) AS progress_count ON (acp.Store_Num = progress_count.Store_Num)

答案 1 :(得分:1)

别名计数(*)然后使用Sum(别名)