sql實現從兩個表擷取欄位組成表資料再插入到函數表中,sql欄位

來源:互聯網
上載者:User

sql實現從兩個表擷取欄位組成表資料再插入到函數表中,sql欄位

  實現此效果說起來比較難以說明,我這裡還是先將實現的效果已圖的形式展示一下吧。


這是兩個表的設計。我想實現的效果舉個例子,以查詢secretaryCharge為例:

點擊“市級”,我將查詢到市級一下所有“區級”的secretaryCharge數目,並通過organizations中的fullName來作為名字,查到的統計數目作為值。得到的效果便是如所示:


具體實現sql語句就是用到join on,sql語句具體如下:

insert @result(fullName,paramer)(select fullName,villageCharge from (select fullName,orgID from organizations where parent=@orgId) as orgInfojoin(select DJCharge.parentOrg as parent ,sum(villageCharge) as villageChargefrom DJCharge,organizations where year=@year and DJCharge.orgID=organizations.orgID and DJCharge.parentOrg in(select distinct orgID from organizations where parent=@orgID)group by DJCharge.parentOrg) as DJChargeInfoon orgInfo.orgID=DJChargeInfo.parent   )

這裡我省略了定義、聲明等過程,此段代碼是begin-end塊中的。用了groupby,不用的話則會統計總數,而不能將子查詢分開統計。

如果需要統計一個表中的多個欄位統計數,join-on還可以繼續使用,代碼例子如下所示:

insert @result (regionFullName,countmale,countfemale)(        select fullName,countmale,countfemale        from        (select fullName,orgID from organizations where parent=@orgID) as orgInfofull join(select count(*) as countmale,SUBSTRING(parentOrg,2,6) AS parent from partyMembers where sex='男' and substring(parentOrg ,2,6)in( select substring(orgID,2,6) AS validOrgID From organizations where parent=@orgID)  group by substring(parentOrg,2,6))as Maleon substring(orgInfo.orgID,2,6)=Male.parent full join(select count(*) as countfemale,substring(parentOrg,2,6)AS parent from partyMembers where sex='女' and substring(parentOrg ,2,6)in( select substring(orgID,2,6) AS validOrgID From organizations where parent=@orgID)  group by substring(parentOrg,2,6))as Femaleon substring(orgInfo.orgID,2,6)=Female.parent )

這裡我用了full join全串連,目的是在顯示時只要組成的表中有一個欄位有值,這一行都得到。查詢效果如下:


如果不使用全串連可能會產生多餘兩行結果。


著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.