SELECT name, salary FROM People WHERE NAMEIN ( SELECTDISTINCTNAMEFROM population WHERE country = "Canada"AND city = "Toronto" ) AND salary >= ( SELECT AVG( salary ) FROM salaries WHERE gender = "Female")
这似乎似乎难以理解,但如果在查询中有许多子查询,那么怎么样?这就是CTEs发挥作用的地方。
with toronto_ppl as ( SELECTDISTINCTname FROM population WHERE country = "Canada" AND city = "Toronto" ) , avg_female_salary as ( SELECTAVG(salary) as avgSalary FROM salaries WHERE gender = "Female" ) SELECTname , salary FROM People WHEREnamein (SELECTDISTINCTFROM toronto_ppl) AND salary >= (SELECT avgSalary FROM avg_female_salary)
with org_structure as ( SELECTid , manager_id FROM staff_members WHERE manager_id ISNULL UNIONALL SELECT sm.id , sm.manager_id FROM staff_members sm INNERJOIN org_structure os ON os.id = sm.manager_id
3.临时函数
如果您想了解有关临时函数的更多信息,请检查此项,但知道如何编写临时功能是重要的原因:
它允许您将代码的块分解为较小的代码块
它适用于写入清洁代码
它可以防止重复,并允许您重用类似于使用Python中的函数的代码。
考虑以下示例:
SELECTname , CASEWHEN tenure < 1THEN"analyst" WHEN tenure BETWEEN1and3THEN"associate" WHEN tenure BETWEEN3and5THEN"senior" WHEN tenure > 5THEN"vp" ELSE"n/a" ENDAS seniority FROM employees
相反,您可以利用临时函数来捕获案例子句。
CREATETEMPORARYFUNCTION get_seniority(tenure INT64) AS ( CASEWHEN tenure < 1THEN"analyst" WHEN tenure BETWEEN1and3THEN"associate" WHEN tenure BETWEEN3and5THEN"senior" WHEN tenure > 5THEN"vp" ELSE"n/a" END ); SELECTname , get_seniority(tenure) as seniority FROM employees
+----+-------+--------+-----------+ | Id | Name | Salary | ManagerId | +----+-------+--------+-----------+ | 1 | Joe | 70000 | 3 | | 2 | Henry | 80000 | 4 | | 3 | Sam | 60000 | NULL | | 4 | Max | 90000 | NULL | +----+-------+--------+-----------+Answer: SELECT a.Name as Employee FROM Employee as a JOIN Employee as b on a.ManagerID = b.Id WHERE a.Salary > b.Salary
# Comparing each month's sales to last month SELECTmonth , sales , sales - LAG(sales, 1) OVER (ORDERBYmonth) FROM monthly_sales # Comparing each month's sales to the same month last year SELECTmonth , sales , sales - LAG(sales, 12) OVER (ORDERBYmonth) FROM monthly_sales