Sql 从多个表中选择,不直接连接
我找不到最好的问题标题来描述我的问题,所以请原谅我的感觉,不管怎么说,这都不准确或误导 表1:UserMasterSql 从多个表中选择,不直接连接,sql,Sql,我找不到最好的问题标题来描述我的问题,所以请原谅我的感觉,不管怎么说,这都不准确或误导 表1:UserMaster UserID username ------------------------------------------- ---------- 04FF9B2B-465E-4933-95D0-22B139177396 Admin 0DF62BD7-49F9-429E-9046-C5E631B501
UserID username
------------------------------------------- ----------
04FF9B2B-465E-4933-95D0-22B139177396 Admin
0DF62BD7-49F9-429E-9046-C5E631B501F3 User
表2平面图
Userid planid
------------------------------------------ ---------
04FF9B2B-465E-4933-95D0-22B139177396 2010
04FF9B2B-465E-4933-95D0-22B139177396 2011
88D68F01-30C8-4C25-B8E2-90CDB5CABC19 2012
表3:PlanSiteMaster
planid siteid
-------- --------
2010 1
2010 6
2010 8
2011 2
2012 6
2012 8
id vendorrate
----------- ------------
1 200000
2 250000
3 31500
4 31500
5 45000
6 650000
7 45000
8 585000
9 585000
10 32400
表4:SiteMaster
planid siteid
-------- --------
2010 1
2010 6
2010 8
2011 2
2012 6
2012 8
id vendorrate
----------- ------------
1 200000
2 250000
3 31500
4 31500
5 45000
6 650000
7 45000
8 585000
9 585000
10 32400
预期结果:
Userid PlanId Sum(Vendorrate)
------ ------ ---------------
简而言之,Usermaster有多个用户。一个用户可以有多个计划,存储在PlanMaster中。一个计划可以有多个站点,存储在PlanSiteMaster中。站点详细信息及其供应商地址存储在SiteMaster中
我需要的是PlanId列表,以及每个用户对应于每个计划的VendorRate之和。
我尝试的是:
select a.planid,Amount from
(select planid,planname,plancreateddate from PlanMaster where status = 1 and userid = @UserId)a,
(select PlanId, Count(1) as SiteCount from PlanSiteMaster where status=1 group by planid) b,
(select sum(CAST(vendorrate as Bigint)) as Amount from SiteMaster where id
in(select siteid from PlanSiteMaster where status=1))c where a.PlanId = b.PlanId and a.PlanId=c.planid;
无法从所有表中提取数据:(
我们将非常感谢您的每一点帮助。请尝试以下查询:
SELECT U.* FROM
(SELECT pm.UserID,pm.PlanId, vs.totalVandorRate
FROM PlanMaster as pm
JOIN (
SELECT p.PalnId ,SUM(s.VandorRate) as totalVandorRate
FROM PlanSiteMaster as p JOIN SiteMaster as s
ON p.SiteId=s.SiteId GROUP BY p.PlanId
) as vs
ON pm.PlanId=vs.PlanId) AS u WHERE u.UserId='88D68F01-30C8-4C25-B8E2-90CDB5CABC19';
在表4中:SiteMaster
id
是siteId
?没有类似于status
的列。有许多列具有不同的名称。为了便于理解,我只是将其更改为必需的列。它工作得很好。但我有点担心性能。因为我刚刚共享了示例数据,但原始表有超过10K行。但是,将整个表分组,然后选择匹配的行,而不是在选定的值上循环,然后将它们添加到临时变量中,这样会更有效地提高性能?无论如何,您不是一个沮丧的开发人员,而是一个专业的开发人员。@sanjeev。如果您有关于性能的问题,您可能应该将其作为一个新问题提问,因为这个问题已经得到了回答。