多表數據鏈接 Left join

一個我寫的實例:其中多表鏈接,一共鏈接了3個表。使用匯集函數SUM,用到了GROUP BY

SELECT a.[UserID],b.[Name],sum (c.[Money]+c.[Bank])as TotalMoney
FROM Table1 a(nolock)
 LEFT JOIN Table2 b(nolock) on a.[UserID] = b.[UserID] 
LEFT JOIN Table3 c(nolock) ON b.[UserID]=c.[UserID] 

WHERE  a.[UserID] = b.[UserID] and a.[UserID] = c.[UserID] and a.[Time] >= '2005-01-01' AND a.[Time] <= '2006-12-31' 

GROUP BY a.[UserID],b.[Name]

ORDER BY a.[Time] DESC 

優化一下
SELECT a.[UserID],b.[Name],sum (c.[Money]+c.[Bank])as TotalMoney
FROM Table1 a(nolock)
LEFT JOIN Table3 c(nolock) ON a.[UserID]=c.[UserID],  Table2 b(nolock) 

WHERE  a.[UserID] = b.[UserID] and a.[Time] >= '2005-01-01' AND a.[Time] <= '2006-12-31' 

GROUP BY a.[UserID],b.[Name]

ORDER BY a.[Time] DESC 

================================================================================
Left Join 語法:
select   *   from
table1   left   join   table2   on   條件1   
left   join   table3   on   條件2   
left   join   table4   on   條件3  
where   條件4

GROUP BY 說明:

group by 

    在select 語句中能夠使用group by 子句將行劃分紅較小的組,而後,使用聚組函數返回每個組的彙總信息,另外,能夠使用having子句限制返回的結果集。group by 子句能夠將查詢結果分組,並返回行的彙總信息Oracle 按照group by 子句中指定的表達式的值分組查詢結果。

   在帶有group by 子句的查詢語句中,在select 列表中指定的列要麼是group by 子句中指定的列,要麼包含聚組函數

   select max(sal),job emp group by job;
   (注意max(sal),job的job並不是必定要出現,但有意義)

   查詢語句的select 和group by ,having 子句是聚組函數惟一出現的地方,在where 子句中不能使用聚組函數。

  select deptno,sum(sal) from emp where sal>1200 group by deptno having sum(sal)>8500 order by deptno;

  當在gropu by 子句中使用having 子句時,查詢結果中只返回知足having條件的組。在一個sql語句中能夠有where子句和having子句。having 與where 子句相似,均用於設置限定條件
 
  where 子句的做用是在對查詢結果進行分組前,將不符合where條件的行去掉,即在分組以前過濾數據,條件中不能包含聚組函數,使用where條件顯示特定的行。
  having 子句的做用是篩選知足條件的組,即在分組以後過濾數據,條件中常常包含聚組函數,使用having 條件顯示特定的組,也能夠使用多個分組標準進行分組。

  查詢每一個部門的每種職位的僱員數
  select deptno,job,count(*) from emp group by deptno,job;
相關文章
相關標籤/搜索