-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqueries.txt
49 lines (46 loc) · 1.63 KB
/
queries.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
-- Create a union all between the Facility Type
-- and FacilityTypeSecondary Columns into one table
create temp table FacilityTypeUnion as
select FacilityId, FacilityType, Risk, InspectionDate from
(
select FacilityId, FacilityType, Risk, InspectionDate from FoodInspections
union all
select
FacilityId, FacilityTypeSecondary, Risk, InspectionDate
from FoodInspections
where FacilityTypeSecondary is not null
);
-- Remove rows with the same FacilityIds by
-- only taking the latest InspectionDate
create temp table RiskPerFacilityId as
select
FacilityId, FacilityType, Risk, InspectionDate
from
(
select
FacilityId, FacilityType, Risk, InspectionDate,
row_number() over (partition by FacilityId order by InspectionDate desc) row_num
from FacilityTypeUnion
) derivedTable where derivedTable.row_num = 1;
-- calculate average risk and group by FacilityType
select FacilityType, avg(Risk) as AverageRisk from RiskPerFacilityId group by FacilityType;
--
--
-- Query run against the Original dataset
--
-- create temp table FacilityTypeUnion as
-- select FacilityType, Risk, InspectionDate from Food_Inspections;
--
-- create temp table RiskPerFacilityType as
-- select
-- FacilityType, Risk, InspectionDate
-- from
-- (
-- select
-- FacilityType, Risk, InspectionDate,
-- row_number() over (partition by FacilityType order by InspectionDate desc) row_num
-- from FacilityTypeUnion
-- ) derivedTable where derivedTable.row_num = 1;
--
-- -- calculate average risk and group by FacilityType
-- select FacilityType, avg(Risk) as AverageRisk from RiskPerFacilityType group by FacilityType;