I have two working reports / data-sources, but want to combine them into one.
I'm not too sure about which sections should go where, and what needs to go inside what bracket.
Some help regarding combining these into one report would be appreciated, the link field between both reports is the job.job_number field.
Edit: What I would like to see at the end is a report that gives me the following headings:
ALL FROM REPORT / DATASOURCE ONE
Job.Job_number 410000378
job.site_code 1372
job.job_entry_date 31/01/2019 17:45:23
job.actual_comp_date 04/06/2019
central_site.site_name HIGH STREET, NEWPORT
area.area_name NEWPORT
zone_1_area_check ZONE 1 AREA
day_logged Thu
week_on_site 5
job_type.job_type_code FLY1
job_type.job_type_name FLYTIP ZONE 1 AREA
Gang_Photos Photos Linked
Photo_Count 2
Photo Check Pass
Arrived_on_time_check Pass
KPI_PASS_FAIL Pass
KPI_PENALTY_INSTANCES 0
KPI_STATUS_CHECK Pass
JOB_KPI KPI 2 - FLY TIPPING
KPI_POINTS 25
Week_dashboard Current Week
Month_dashboard Current Month
Quarter_dashboard Current Quarter
ALL FROM DATA-SOURCE TWO:
clock_start 01/02/2019 08:00:00
target_time 01/02/2019 12:00:00
priority.priority_code GC06
First report / data-source code:
select
job.job_number,
job.job_entry_date,
job.site_code,
central_site.site_name,
area.area_name as Parish,
JOB.JOB_ENTRY_DATE as Job_logged,
priority.priority_code,
priority.priority_name,
job.target_comp_date as Target_On_Site,
job.actual_START_date as Actual_On_Site,
JOB.actual_COMP_DATE as Job_Completed_Time,
CASE
WHEN central_site.site_code in
('456','1372','1373','1426','1432','2251',
'3202','3206','4017','9978','9979','9980',
'9981','9982','9983','9984','9985','9986',
'9987','9988','9989','9990','9991','9992',
'9993','9994','9995','9996','9997','9998',
'9999')
THEN 'Zone 1 Area'
ELSE ''
END as ZONE_1_AREA_CHECK,
TO_CHAR(job.job_entry_date, 'Dy') as DAY_LOGGED,
TO_CHAR(job.actual_start_date, 'IW') as WEEK_ON_SITE,
job_type.job_type_code,
job_type.job_type_name,
-- CHECK TO SEE IF 2 PHOTOS HAVE BEEN TAKEN ON JOB
CAST(CASE WHEN document_link.entity_key IS NULL THEN 'No Photos' ELSE
'Photos Linked' END as VARCHAR (20)) as gang_photos,
(SELECT COUNT(document_link.entity_key) FROM document_link WHERE
document_link.entity_key =CAST( job.job_number as VARCHAR (15)) AND
document_link.entity_type = 'JOB' AND
document_link.document_notes LIKE 'Photo added by_%' ) as Photo_count,
CASE
WHEN ROUND ((SELECT COUNT(document_link.entity_key) FROM document_link WHERE
document_link.entity_key =CAST( job.job_number as VARCHAR (15)) AND
document_link.entity_type = 'JOB'),2) >=2 then 'Pass' else 'FAIL' end as
Photo_Check,
-- kpi tracker
CASE
WHEN job.actual_start_date is null AND current_date < job.target_comp_date
THEN 'Not arrived on site yet'
WHEN job.actual_start_date is null AND current_date > job.target_comp_date
THEN 'FAIL (2)'
when job.actual_start_date <= job.target_comp_date then 'Pass'
when job.actual_start_date > job.target_comp_date then 'FAIL'
ELSE 'Overdue' END as Arrived_on_time_check,
-- KPI arrive on site and 2 photos check
CASE
WHEN job.actual_start_date <= job.target_comp_date AND
ROUND ((SELECT COUNT(document_link.entity_key) FROM document_link WHERE
document_link.entity_key =CAST( job.job_number as VARCHAR (15)) AND
document_link.entity_type = 'JOB'),2) >=2 then 'Pass' else 'Fail' end as
KPI_PASS_FAIL,
-- KPI Instances of penalty
CASE
-- arrived on site in time and 2+ photos = 0 penalty (pass)
WHEN job.actual_start_date <= job.target_comp_date AND
ROUND ((SELECT COUNT(document_link.entity_key) FROM document_link WHERE
document_link.entity_key =CAST( job.job_number as VARCHAR (15))
AND document_link.entity_type = 'JOB'),2) >=2 then '0'
-- arrived on time but no photos attached = 1 penalty (FAIL PHOTOS)
WHEN job.actual_start_date <= job.target_comp_date AND
ROUND ((SELECT COUNT(document_link.entity_key) FROM document_link WHERE
document_link.entity_key =CAST( job.job_number as VARCHAR (15))
AND document_link.entity_type = 'JOB'),2) <=1 then '1'
--arrived on site late BUT 2+ PHOTOS = manual calculation (FAIL TIME)
WHEN job.actual_start_date > job.target_comp_date AND
ROUND ((SELECT COUNT(document_link.entity_key) FROM document_link WHERE
document_link.entity_key =CAST( job.job_number as VARCHAR (15))
AND document_link.entity_type = 'JOB'),2) >=2 THEN 'Manual Calculation -
Time Fail'
-- ARRIVED LATE AND NOT ENOUGH PHOTOS (FAIL TIME AND PHOTOS)
WHEN job.actual_start_date > job.target_comp_date AND
ROUND ((SELECT COUNT(document_link.entity_key) FROM document_link WHERE
document_link.entity_key =CAST( job.job_number as VARCHAR (15))
AND document_link.entity_type = 'JOB'),2) <=1 THEN 'Manual Calculation -
Time and Photo Fail'
else 'Check' end as KPI_PENALTY_INSTANCES,
-- KPI STATUS CHECK
CASE
-- arrived on site in time and 2+ photos = 0 penalty (pass)
WHEN job.actual_start_date <= job.target_comp_date AND
ROUND ((SELECT COUNT(document_link.entity_key) FROM document_link WHERE
document_link.entity_key =CAST( job.job_number as VARCHAR (15))
AND document_link.entity_type = 'JOB'),2) >=2 then 'PASS'
-- arrived on time but no photos attached = 1 penalty (FAIL PHOTOS)
WHEN job.actual_start_date <= job.target_comp_date AND
ROUND ((SELECT COUNT(document_link.entity_key) FROM document_link WHERE
document_link.entity_key =CAST( job.job_number as VARCHAR (15))
AND document_link.entity_type = 'JOB'),2) <=1 then 'FAIL - PHOTOS'
--arrived on site late BUT 2+ PHOTOS = manual calculation (FAIL TIME)
WHEN job.actual_start_date > job.target_comp_date AND
ROUND ((SELECT COUNT(document_link.entity_key) FROM document_link WHERE
document_link.entity_key =CAST( job.job_number as VARCHAR (15))
AND document_link.entity_type = 'JOB'),2) >=2 THEN 'FAIL - ARRIVED LATE'
-- ARRIVED LATE AND NOT ENOUGH PHOTOS (FAIL TIME AND PHOTOS)
WHEN job.actual_start_date > job.target_comp_date AND
ROUND ((SELECT COUNT(document_link.entity_key) FROM document_link WHERE
document_link.entity_key =CAST( job.job_number as VARCHAR (15))
AND document_link.entity_type = 'JOB'),2) <=1 THEN 'FAIL - TIME AND PHOTOS'
WHEN job.actual_START_date is NULL then 'FAIL - ARRIVED TIME BLANK'
else 'Check' end as KPI_STATUS_CHECK,
-- JOB KPI ATTRIBUTE LOOK UP IN GJOB TABLE
(SELECT attribute_value.attrib_value_name FROM attribute_value WHERE
attribute_value.attrib_type_code = 'GJOB'
AND attribute_value.attrib_value_code = job_type.job_type_code) as JOB_KPI,
-- JOB KPI PENALTY POINTS LOOK UP IN GJOB TABLE
(SELECT attribute_value.attrib_value_nom FROM attribute_value WHERE
attribute_value.attrib_type_code = 'GJOB'
AND attribute_value.attrib_value_code = job_type.job_type_code) as
KPI_POINTS,
-- FIELDS FOR USE IN DASHBOARD WIDGETS
CASE
when job.actual_comp_date >= trunc(trunc(SYSDATE,'IW')-1,'IW') AND
job.actual_comp_date <=trunc(SYSDATE,'IW') then 'Previous Week'
when job.actual_comp_date >=trunc(SYSDATE,'IW') AND job.actual_comp_date <=
SYSDATE then 'Current Week'
else ''
end as Week_Dashboard,
CASE
when job.actual_comp_date >= trunc(trunc(SYSDATE,'MM')-1,'MM') AND
job.actual_comp_date <=trunc(SYSDATE,'MM') then 'Previous Month'
when job.actual_comp_date >=trunc(SYSDATE,'MM') AND job.actual_comp_date <=
SYSDATE then 'Current Month'
else ''
end as Month_Dashboard,
CASE
when job.actual_comp_date >= trunc(trunc(SYSDATE,'IW')-1,'Q') AND
job.actual_comp_date <=trunc(SYSDATE,'Q') then 'Previous Quarter'
when job.actual_comp_date >=trunc(SYSDATE,'Q') AND job.actual_comp_date <=
SYSDATE then 'Current Quarter'
else ''
end as Quarter_Dashboard
from
job
left join enquiry on job.job_number = enquiry.job_number
left join defect on job.job_number = defect.job_number
left join defect_type on defect_type.defect_type_code = defect.defect_type
inner join central_site on job.site_code = central_site.site_code
inner join area on central_site.area_code = area.area_code
left join central_enquiry on central_enquiry.enquiry_number =
enquiry.enquiry_number
left join enquiry_cust_link on central_enquiry.enquiry_number =
enquiry_cust_link.enquiry_number
left join enquiry_subject on enquiry_subject.subject_code =
central_enquiry.subject_code
left join type_of_service on type_of_service.service_code =
enquiry_subject.service_code
inner join priority on priority.priority_code = job.priority_code
inner join JOB_STATUS_LOG on JOB.JOB_NUMBER = JOB_STATUS_LOG.JOB_NUMBER
and job.job_log_number = job_status_log.job_log_number
inner join JOB_STATUS on JOB_STATUS.STATUS_CODE = JOB_STATUS_LOG.STATUS_CODE
inner join job_type on job_type.job_type_key = job.job_type_key
inner join priority on priority.priority_code = job.priority_code
LEFT OUTER JOIN
(SELECT DISTINCT
job.job_number,
document_link.entity_key,
(SELECT COUNT(document_link.entity_key) FROM document_link WHERE
document_link.entity_key =CAST( job.job_number as VARCHAR (15)) AND
document_link.entity_type = 'JOB' AND
document_link.document_notes LIKE 'Photo added by_%' ) as Photo_count
FROM
job
LEFT OUTER JOIN
document_link
ON
document_link.entity_key =CAST( job.job_number as VARCHAR (15)) AND
document_link.entity_type = 'JOB' AND
document_link.document_notes LIKE 'Photo added by_%') document_link
ON
document_link.job_number = job.job_number
where
job_status_log.allocated_officer = 'IDVE' and
job_status_log.status_code in ('5100','5200','5300','5400')
order by
job.job_number
Second Report / Data-Source Code:
select job_number, priority_code, job_entry_date, clock_start,
target_comp_date,
case
when to_char(target_time, 'Dy', 'NLS_DATE_LANGUAGE=ENGLISH') = 'Fri'
and floor((target_time - trunc(target_time)) * 24) >= 17
then target_time + 2 + 63/24
when floor((target_time - trunc(target_time)) * 24) >= 17
then target_time + 15/24
else target_time
end as target_time
from (
select job_number, priority_code, job_entry_date, clock_start,
TARGET_COMP_DATE,
CASE
WHEN PRIORITY_CODE IN ('GC01','GC02','GC03','GC04','GC05','GC06','GC07')
THEN
clock_start
+ case priority_code
when 'GC01' then 1
when 'GC02' then 2
when 'GC03' then 0.5
when 'GC04' then 1
when 'GC05' then 2
when 'GC06' then 4
when 'GC07' then 24
end
/ 24
ELSE
TARGET_COMP_DATE END as target_time
from (
select job_number, priority_code, job_entry_date, target_comp_date,
case
when to_char(job_entry_date, 'Dy', 'NLS_DATE_LANGUAGE=ENGLISH') = 'Fri'
and floor((job_entry_date - trunc(job_entry_date)) * 24) >= 17
then trunc(job_entry_date) + 80/24
when to_char(job_entry_date, 'Dy', 'NLS_DATE_LANGUAGE=ENGLISH') = 'Sat'
then trunc(job_entry_date) + 56/24
when to_char(job_entry_date, 'Dy', 'NLS_DATE_LANGUAGE=ENGLISH') = 'Sun'
or floor((job_entry_date - trunc(job_entry_date)) * 24) >= 17
then trunc(job_entry_date) + 32/24
when floor((job_entry_date - trunc(job_entry_date)) * 24) < 8
then trunc(job_entry_date) + 8/24
else job_entry_date
end as clock_start
from job
)
)
Related
I have a query below that I need to get a count where Incident Records = 0. The first level is a summary of the records it grabs to calculate totals. I tried using COUNT(INCIDENTS!='0') but it apparently is not working though it does not error out. How would I get this count? This is in Snowflake if that is a factor. The case statement: CASE WHEN SUM(INCIDENTS) = '0' THEN '0' ELSE COUNT(INCIDENTS!='0') END AS INCIDENTS Works but the 2nd line which references those Incidents seems to only give a count but not the result of the Case Statement before it:
SELECT DRIVER_NAME, DRIVER_ID, CSC, SUM(DISTINCT(OBSERVATIONS)) AS OBSERVATIONS, --SUM(DISTINCT(INCIDENTS)) AS INCIDENTS_SUM_DISTINCT,
--COUNT(INCIDENTS) AS INCIDENTS,
COUNT(INCIDENTS!='0'),
CASE WHEN SUM(INCIDENTS) = '0' THEN '0' ELSE COUNT(INCIDENTS!='0') END AS INCIDENTS,
(COUNT(INCIDENTS!='0') / SUM(DISTINCT(OBSERVATIONS))) * 100 AS FREQUENCY_PERCENT,
1 AS GOAL, (SUM(SIX_TEN_MPH) / SUM(DISTINCT(OBSERVATIONS))) * 100 AS SIX_TEN_PERCENT,
(SUM(ELEVEN_FIFTEEN_MPH) / SUM(DISTINCT(OBSERVATIONS))) * 100 AS ELEVEN_FIFTEEN_PERCENT,
(SUM(SIXTEEN_PLUS_MPH) / SUM(DISTINCT(OBSERVATIONS))) * 100 AS SIXTEEN_PLUS_PERCENT
--SPEED_LIMIT, SPEED, DIFFERENCE, REPORT_DATE, TIME,
FROM
(
SELECT A.DRIVER_NAME AS DRIVER_NAME, A.DRIVER_ID AS DRIVER_ID, C.TRC_TERMINAL AS CSC, A.OBSERVATIONS AS OBSERVATIONS,
A.INCIDENTS AS INCIDENTS, B.SPEED_LIMIT AS SPEED_LIMIT, B.SPEED AS SPEED, B.DIFFERENCE AS DIFFERENCE,
A.REPORT_DATE AS REPORT_DATE, B.TIME AS TIME,
CASE WHEN DIFFERENCE >= 6 AND DIFFERENCE <= 10 THEN '1' WHEN DIFFERENCE IS NULL THEN '0' ELSE '0' END AS SIX_TEN_MPH,
CASE WHEN DIFFERENCE > 10 AND DIFFERENCE <= 15 THEN '1' WHEN DIFFERENCE IS NULL THEN '0' ELSE '0' END AS ELEVEN_FIFTEEN_MPH,
CASE WHEN DIFFERENCE > 15 THEN '1' WHEN DIFFERENCE IS NULL THEN '0' ELSE '0' END AS SIXTEEN_PLUS_MPH
FROM "PROD"."PUBLIC"."SG_DRIVER_TREND" A
LEFT JOIN "PROD"."PUBLIC"."SG_DRIVER_INCIDENTS" B
ON A.DRIVER_ID = B.DRIVER_ID
LEFT JOIN "PROD"."PUBLIC"."TMW_TRACTORPROFILE" C
ON B.Vehicle = C.TRC_NUMBER
WHERE A.DRIVER_ID != ''
AND A.REPORT_DATE BETWEEN '2022-07-01' AND '2022-07-31'
AND B.TIME BETWEEN '2022-07-01' AND '2022-07-31'
AND SUBSTRING(B.TIME, 0, 10) <= A.REPORT_DATE -- Less than or equal to report date
AND SUBSTRING(B.TIME, 0, 10) > SUBSTRING(DATEADD(week,-1, A.REPORT_DATE), 0, 10) -- Greater than 1 week ago
UNION
--SELECT A.DRIVER_NAME AS DRIVER_NAME, A.DRIVER_ID AS DRIVER_ID, C.TRC_TERMINAL AS CSC, A.OBSERVATIONS AS OBSERVATIONS,
-- A.INCIDENTS AS INCIDENTS, B.SPEED_LIMIT AS SPEED_LIMIT, B.SPEED AS SPEED, B.DIFFERENCE AS DIFFERENCE,
-- A.REPORT_DATE AS REPORT_DATE, B.TIME AS TIME,
SELECT DISTINCT(A.DRIVER_NAME) AS DRIVER_NAME, A.DRIVER_ID AS DRIVER_ID,
C.TRC_TERMINAL AS CSC,
--'UPT' AS CSC,
A.OBSERVATIONS AS OBSERVATIONS,
'0' AS INCIDENTS, '0' AS SPEED_LIMIT, '0' AS SPEED, '0' AS DIFFERENCE,
A.REPORT_DATE AS REPORT_DATE, '' AS TIME,
'0' AS SIX_TEN_MPH,
'0' AS ELEVEN_FIFTEEN_MPH,
'0' AS SIXTEEN_PLUS_MPH
FROM "PROD"."PUBLIC"."SG_DRIVER_TREND" A
LEFT JOIN "PROD"."PUBLIC"."SG_DRIVER_INCIDENTS" B
ON A.DRIVER_ID = B.DRIVER_ID
-- AND SUBSTRING(B.TIME, 0, 10) <= A.REPORT_DATE -- Less than or equal to report date
-- AND SUBSTRING(B.TIME, 0, 10) > SUBSTRING(DATEADD(week,-1, A.REPORT_DATE), 0, 10) -- Greater than 1 week ago
INNER JOIN "PROD"."PUBLIC"."TMW_TRACTORPROFILE" C
ON B.Vehicle = C.TRC_NUMBER
WHERE NOT EXISTS (SELECT DRIVER_ID FROM "PROD"."PUBLIC"."SG_DRIVER_INCIDENTS" D
WHERE A.DRIVER_ID = D.DRIVER_ID
AND D.TIME BETWEEN '2022-07-01' AND '2022-07-31'
AND SUBSTRING(D.TIME, 0, 10) <= A.REPORT_DATE -- Less than or equal to report date
AND SUBSTRING(D.TIME, 0, 10) > SUBSTRING(DATEADD(week,-1, A.REPORT_DATE), 0, 10) -- Greater than 1 week ago
)
AND A.DRIVER_ID != '' AND A.INCIDENTS = '0'
AND A.REPORT_DATE BETWEEN '2022-07-01' AND '2022-07-31'
--AND B.DRIVER_ID IS NULL --<-- For LEFT JOIN
ORDER BY DRIVER_ID
)
--WHERE INCIDENTS != 0
GROUP BY DRIVER_ID, DRIVER_NAME, CSC
ORDER BY DRIVER_ID
This line:
CASE WHEN SUM(INCIDENTS) = '0' THEN '0' ELSE COUNT(INCIDENTS!='0') END AS INCIDENTS seems to give me the correct number of incidents but when I try and copy it into this line as the Incident Count: (COUNT(INCIDENTS!='0') / SUM(DISTINCT(OBSERVATIONS))) * 100 AS FREQUENCY_PERCENT
like: (COUNT(CASE WHEN SUM(INCIDENTS) = '0' THEN '0' ELSE COUNT(INCIDENTS!='0') END) / SUM(DISTINCT(OBSERVATIONS))) * 100 AS FREQUENCY_PERCENT, I get the following error:
SQL compilation error: Aggregate functions cannot be nested: [SUM(CAST("values".INCIDENTS AS FLOAT))] nested in [COUNT(IFF((SUM(CAST("values".INCIDENTS AS FLOAT))) = (CAST('0' AS FLOAT)), TO_NUMBER('0', 18, 0), COUNT(CAST("values".INCIDENTS != '0' AS BOOLEAN))))]
I have seen examples online of nested Aggregate Functions working. Code examples are appreciated.
The first line:
CASE WHEN SUM(INCIDENTS) = '0' THEN '0' ELSE COUNT(INCIDENTS!='0') END
is a conditional aggreation, simplified to COUNT_IF:
COUNT_IF(INCIDENTS != '0') AS INCIDENTS
The second one:
COUNT_IF(INCIDENTS != '0')/NULLIF(SUM(DISTINCT OBSERVATIONS)),0) * 100
AS FREQUENCY_PERCENT
It is always good to secure against division by 0, thus NULLIF(exp, 0).
i have this query
SELECT case
when {{aggtime}} = 'HOURLY' then parsedatetime(formatdatetime("PUBLIC"."ORDERS"."CREATED_AT", 'yyyyMMddHH'), 'yyyyMMddHH')
when {{aggtime}} = 'DAILY' then CAST("PUBLIC"."ORDERS"."CREATED_AT" AS date)
when {{aggtime}} = 'WEEKLY' then dateadd('day', CAST((1 - CASE WHEN ((iso_day_of_week("PUBLIC"."ORDERS"."CREATED_AT") + 1) % 7) = 0 THEN 7 ELSE ((iso_day_of_week("PUBLIC"."ORDERS"."CREATED_AT") + 1) % 7) END) AS long), CAST("PUBLIC"."ORDERS"."CREATED_AT" AS date))
when {{aggtime}} = 'MONTHLY' then parsedatetime(formatdatetime("PUBLIC"."ORDERS"."CREATED_AT", 'yyyyMM'), 'yyyyMM')
when {{aggtime}} = 'YEARLY' then parsedatetime(formatdatetime("PUBLIC"."ORDERS"."CREATED_AT", 'yyyy'), 'yyyy')
END
AS "CREATED_AT", sum("PUBLIC"."ORDERS"."QUANTITY") AS "sum"
FROM "PUBLIC"."ORDERS"
WHERE year(CREATED_AT)=2020 and month(CREATED_AT) = 1 and day(CREATED_AT) = 01
GROUP BY "CREATED_AT"
i need the where clause only when {{aggtime}}='HOURLY', otherwise i need only the year
How can i achieve it ?
ps :. {{aggtime}} is a parameter for Metabase
I have a query that does not return the expense value if the drvalue(Debtor Value) is equal to 0 or NULL,
If i change the drvalue to any value greater than 0, query returns the expenses value.
Drvalue is a sum of all the values for a specific period
Below is the query
SELECT f.vehiclenumber,f.fleettype,f.IsCreditor,
ISNULL(SUM(l.DrValue),0) AS drvalue,
CASE WHEN iscreditor=1 then Sum (DrValue) - Sum(CrValue) else null end AS Profit,
sum(l.CrValue) AS CrValue ,
sum(l.distance) AS LoadDist,
sum(l.DrValue)/DDist AS DRVal ,
d.Liters AS Liters,d.ddist AS DDist, d.DDiesel AS DDiesel, d.DieselCost AS dieslCost,
(MAX(isnull(l.Closingkm,0))-MIN(isnull(l.OpeningKM,0))) AS [CO],ISNULL(SUM(l.DrValue),0) / CASE WHEN (isnull(MAX(l.Closingkm),0)-MIN(isnull(l.OpeningKM,0)))=0 THEN 1 ELSE (isnull(MAX(l.Closingkm),0)-MIN(isnull(l.OpeningKM,0))) END AS TotalCPK,
(d.DieselCost/sum(l.DrValue)) * 100 AS DieselPerc,
SUM(jobdetails.total) AS Expenses,
count(l.vehicleNo) AS LoadCount
FROM tblVehicle AS f
LEFT JOIN (SELECT Vehicleno, loaddate, DrValue, CrValue,Distance, OpeningKM, closingkm FROM tblloads WHERE DrValue IS NOT NULL) AS l ON f.VehicleNumber = l.VehicleNo AND l.loaddate >= '2020-06-01' and l.loaddate <= '2020-06-30'
LEFT JOIN (SELECT fleet , NULLIF(SUM(Liters),0) AS Liters,NULLIF(sum(distance),0) AS DDist, NULLIF(sum(distance)/ CASE WHEN sum(Liters)=0 THEN 1 ELSE sum(Liters) END,0) AS DDiesel, NULLIF(SUM (Manual_Amount),0) AS DieselCost FROM tblinput
WHERE [Date] >= '2020-06-01' And [Date] <= '2020-06-30'
GROUP BY Fleet) AS d ON l.VehicleNo = d.Fleet
LEFT JOIN (SELECT jd.fleet, SUM(Total) AS total From tblJobDetails jd, tbljobcards WHERE tbljobcards.JobID = jd.jobid AND jobdate >= '2020-06-01' AND jobdate <= '2020-06-30' GROUP BY jd.fleet) AS jobdetails ON jobdetails.fleet = l.vehicleno
WHERE VehicleCategory <> 'T'
GROUP BY f.vehiclenumber,f.fleettype,f.IsCreditor,d.Liters,d.ddist, d.DDiesel,d.DieselCost
ORDER BY fleettype
RESULTS
I have created SQL query which returns the total number of days in a month a person was present,now I want to add the total column and the 3 type of leaves column i.e. [Casual Leave], [Paid Leave], [Complimentary Leave].
In short I want to add the total column with [Casual Leave], [Paid Leave]and [Complimentary Leave].
My query is as below:
;WITH ToPivot
AS ( SELECT
time_tracker.date,
Users.FirstName + ' ' + Users.LastName AS username,
(CASE
WHEN
(
(datepart(hour, chk_in)) is null
OR (datepart(hour, chk_out)) is null
)
then
0
WHEN
(
(datepart(hour, chk_in)) >= 12
OR (datepart(hour, chk_out)) < 16
AND ((datepart(hour, chk_out)) - (datepart(hour, chk_in))) < 6
)
THEN
0.5
ELSE
1
END) AS late, TypeOfLeaves.leave_type, Userleavetyp.no_of_days
FROM Users
INNER JOIN time_tracker ON Users.ID = time_tracker.fk_userid
INNER JOIN Userleavetyp ON Users.ID = Userleavetyp.fk_user
INNER JOIN TypeOfLeaves ON Userleavetyp.fk_tol = TypeOfLeaves.ID
WHERE (Users.FK_Status = 1)
),
LateTotals AS (
SELECT T.username, Total = SUM(late),T.leave_type,T.no_of_days
FROM ToPivot AS T
WHERE T.date BETWEEN '2018-07-01' AND '2018-07-31' GROUP BY T.username,T.leave_type,T.no_of_days
)
SELECT distinct(pv2.username) as original ,PV2.*,L.Total
FROM ToPivot AS P
PIVOT (SUM(late) FOR date IN ("2018-07-01", "2018-07-02", "2018-07-03", "2018-07-04", "2018-07-05", "2018-07-06", "2018-07-07", "2018-07-08", "2018-07-09", "2018-07-10", "2018-07-11", "2018-07-12", "2018-07-13", "2018-07-14", "2018-07-15", "2018-07-16", "2018-07-17", "2018-07-18", "2018-07-19", "2018-07-20", "2018-07-21", "2018-07-22", "2018-07-23", "2018-07-24", "2018-07-25", "2018-07-26", "2018-07-27", "2018-07-28", "2018-07-29", "2018-07-30", "2018-07-31")) AS pv1
PIVOT (SUM(no_of_days) FOR leave_type IN ([Casual Leave], [Paid Leave], [Complimentary Leave])) AS pv2
LEFT JOIN LateTotals AS L ON L.username = pv2.username
The output for this code is as below:
I believe you just need to change your select statement as follows.
From this:
SELECT distinct(pv2.username) as original ,PV2.*,L.Total
To this:
SELECT distinct(pv2.username) as original ,PV2.*,L.Total,
CASE WHEN PV2.[Casual Leave] IS NULL THEN 0 ELSE PV2.[Casual Leave] +
CASE WHEN PV2.[Paid Leave] IS NULL THEN 0 ELSE PV2.[Paid Leave] +
CASE WHEN PV2.[Complimentary Leave] IS NULL THEN 0 ELSE PV2.[Complimentary Leave]
AS [Total Leave]
I have the below case expression.
SELECT end_dt,
CASE WHEN TO_CHAR(A.END_DT,'MM/DD/YYYY') = '01/01/3000' THEN ''
WHEN TO_CHAR(A.END_DT,'MM/DD/YYYY') > TO_CHAR(SYSDATE,'MM/DD/YYYY') THEN TO_CHAR(SYSDATE,'MM/DD/YYYY')
ELSE TO_CHAR(A.END_DT,'MM/DD/YYYY')
END ENDDATE,
CASE WHEN TO_CHAR(A.END_DT,'YYYYMM') = '300001' THEN ''
WHEN TO_CHAR(A.END_DT,'YYYYMM') > TO_CHAR(SYSDATE,'YYYYMM') THEN TO_CHAR(SYSDATE,'YYYYMM')
ELSE TO_CHAR(A.END_DT,'YYYYMM')
END ENDDATE_YYYYMM,
CASE WHEN TO_CHAR(A.END_DT,'YYYY') = '3000' THEN ''
WHEN TO_CHAR(A.END_DT,'YYYY') > TO_CHAR(SYSDATE,'YYYY') THEN TO_CHAR(SYSDATE,'YYYY')
WHEN TO_CHAR(A.END_DT,'YYYY') > TO_CHAR(SYSDATE,'YYYY') THEN TO_CHAR(SYSDATE,'YYYY')
ELSE TO_CHAR(A.END_DT,'YYYY')
END ENDDATE_YYYY
FROM A
LEFT D ON A.ID = D.ID
WHERE 1=1
ORDER BY 1
OutPut:
End_dt ENDDATE ENDDATE_YYYYMM ENDDATE_YYYY
12/5/2012 14:33:24 01/05/2018 201212 2012
Expected output:
End_dt ENDDATE ENDDATE_YYYYMM ENDDATE_YYYY
12/5/2012 14:33:24 12/5/2012 201212 2012
Why do I get a result of 01/05/2018 and not 12/5/2012?
You're doing string comparisons on dates. Stop. Do date comparisons on dates.
The string '12/5/2012' is greater than the string '01/05/2018' because 1 is greater than 0. Oracle is performing a binary comparison.
SQL> select *
2 from dual
3 where '12/5/2012' > '01/05/2018';
D
-
X
Stop converting all your dates to strings and all will be well
SQL> select *
2 from dual
3 where date '2018-05-01' > date '2012-05-12';
D
-
X
Incidentally, the empty string '' is equivalent to NULL in Oracle.
Your query should look like:
CASE WHEN A.END_DT = date '3000-01-01' then null
WHEN A.END_DT > SYSDATE THEN TO_CHAR(SYSDATE,'MM/DD/YYYY')
ELSE TO_CHAR(A.END_DT,'MM/DD/YYYY')
END ENDDATE,
Don't do date comparisons as strings. It works for the other values, because you have the right format -- YYYYMMDD (or a partial piece of that).
Try this logic:
SELECT end_dt,
(CASE WHEN TO_CHAR(A.END_DT, 'MM/DD/YYYY') = '01/01/3000' THEN ''
WHEN A.END_DT > SYSDATE
THEN TO_CHAR(SYSDATE, 'MM/DD/YYYY')
ELSE TO_CHAR(A.END_DT, 'MM/DD/YYYY')
END) as ENDDATE,
(CASE WHEN TO_CHAR(A.END_DT, 'YYYYMM') = '300001' THEN ''
WHEN TO_CHAR(A.END_DT, 'YYYYMM') > TO_CHAR(SYSDATE, 'YYYYMM')
THEN TO_CHAR(SYSDATE,'YYYYMM')
ELSE TO_CHAR(A.END_DT,'YYYYMM')
END) as ENDDATE_YYYYMM,
(CASE WHEN TO_CHAR(A.END_DT, 'YYYY') = '3000' THEN ''
WHEN TO_CHAR(A.END_DT, 'YYYY') > TO_CHAR(SYSDATE, 'YYYY')
THEN TO_CHAR(SYSDATE, 'YYYY')
WHEN TO_CHAR(A.END_DT, 'YYYY') > TO_CHAR(SYSDATE,'YYYY')
THEN TO_CHAR(SYSDATE, 'YYYY')
ELSE TO_CHAR(A.END_DT, 'YYYY')
END) as ENDDATE_YYYY