SELECT name, salary FROM People WHERE NAMEIN(SELECTDISTINCTNAMEFROMpopulationWHEREcountry="Canada"ANDcity="Toronto") ANDsalary>=( SELECT AVG(salary) FROM salaries WHERE gender="Female")
这似乎似乎难以理解,但如果在查询中有许多子查询,那么怎么样?这就是CTEs发挥作用的地方。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
with toronto_ppl as ( SELECTDISTINCT name FROM population WHERE country = "Canada" AND city = "Toronto" ) , avg_female_salary as ( SELECTAVG(salary) as avgSalary FROM salaries WHERE gender = "Female" ) SELECT name , salary FROM People WHERE name in (SELECTDISTINCTFROM toronto_ppl) AND salary >= (SELECT avgSalary FROM avg_female_salary)
with org_structure as ( SELECT id, 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
SELECT name, CASEWHEN tenure <1THEN "analyst" WHEN tenure BETWEEN1and3THEN "associate" WHEN tenure BETWEEN3and5THEN "senior" WHEN tenure >5THEN "vp" ELSE "n/a" ENDAS seniority FROM employees
临时函数来捕获案例子句:
1 2 3 4 5 6 7 8 9 10 11
CREATE TEMPORARY FUNCTION 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 ); SELECT name , get_seniority(tenure) as seniority FROM employees
SELECT Name , GPA , ROW_NUMBER() OVER (ORDERBY GPA desc) , RANK() OVER (ORDERBY GPA desc) , DENSE_RANK() OVER (ORDERBY GPA desc) FROM student_grades
ROW_NUMBER()返回每行开始的唯一编号。当存在关系时(例如,BOB vs Carrie),ROW_NUMBER()如果未定义第二条标准,则任意分配数字。Rank()返回从1开始的每行的唯一编号,除了有关系时,Rank()将分配相同的数字。同样,差距将遵循重复的等级。dense_rank()类似于Rank(),除了重复等级后没有间隙。请注意,使用dense_rank(),Daniel排名第3,而不是第4位。