Closed. This question is not written in English. It is not currently accepting answers.
Stack Overflow is an English-only site. The author must be able to communicate in English to understand and engage with any comments and/or answers their question receives. Don't translate this post for the author; machine translations can be inaccurate, and even human translations can alter the intended meaning of the post.
Closed 4 days ago.
This post was edited and submitted for review 4 days ago.
Improve this question
I'm creating a quarterly report of item usage in Firebird, and got stuck at this point:
The select below is working, but it brings me the monthly usage of last 3 months like the image below:
Script:
SELECT
--(SELECT SUM(L.QTDE) FROM GELANSAI L WHERE L.CONSOL = 'T' AND (L.MES = (EXTRACT(MONTH FROM DATEADD(-1 MONTH TO CURRENT_DATE))) AND L.ANO = 2023) GROUP BY L.ITEM) AS CONSUMO1,
--(SELECT SUM(L.QTDE) FROM GELANSAI L WHERE L.CONSOL = 'T' AND (L.MES = (EXTRACT(MONTH FROM DATEADD(-2 MONTH TO CURRENT_DATE))) AND L.ANO = 2022) GROUP BY L.ITEM) AS CONSUMO2,
--(SELECT SUM(L.QTDE) FROM GELANSAI L WHERE L.CONSOL = 'T' AND (L.MES = (EXTRACT(MONTH FROM DATEADD(-3 MONTH TO CURRENT_DATE))) AND L.ANO = 2022) GROUP BY L.ITEM) AS CONSUMO3,
C.MES,
C.ANO,
L.ITEM,
I.NOME,
I.UNI_CON,
I.CONVER,
I.UNI_COMP,
MAX(I.EST_MAX) EST_MAXIMO,
MAX(I.CUSTO) PRECO,
MAX(EST_MIN) EST_MINIMO,
MAX(I.ESTOQUE) ESTOQUE,
SUM(L.QTDE) QUANTIDADE
FROM GECADSAI C INNER JOIN GELANSAI L ON C.ANO = L.ANO AND C.MES = L.MES AND C.DOC = L.DOC
LEFT JOIN GEITENS I ON L.ITEM = I.COD
WHERE (((C.MES = (EXTRACT(MONTH FROM DATEADD(-1 MONTH TO CURRENT_DATE))) AND C.ANO = 2023 ))
OR ((C.MES = (EXTRACT(MONTH FROM DATEADD(-2 MONTH TO CURRENT_DATE)))) AND C.ANO = 2022)
OR (C.MES = (EXTRACT(MONTH FROM DATEADD(-3 MONTH TO CURRENT_DATE))) AND C.ANO = 2022))
AND C.CDC NOT BETWEEN 9901 AND 9999
AND I.REF = 1
AND L.CONSOL = 'T'
AND C.CONSOL = 'T'
GROUP BY L.ITEM, I.NOME, C.ANO, C.MES, I.UNI_CON, I.VLRMED, I.UNI_COMP, I.CONVER
Result:
But, as you can see, the QUANTIDADE column split monthly line by line the total usage.
ITEM_NAME
MONTH
USAGE
ITEM A
JAN
7000
ITEM A
DEZ
3000
ITEM A
NOV
4000
ITEM B
JAN
200
ITEM B
DEZ
350
ITEM B
NOV
500
And I'd like to, each month of consumption to be a column of my select, so, it will be something like this:
ITEM_NAME
JAN
DEZ
NOV
ITEM A
7000
3000
4000
ITEM B
200
350
500
I also tried the commented subselect, but it will for sure returns me, multiple rows error.
SELECT
--(SELECT SUM(L.QTDE) FROM GELANSAI L WHERE L.CONSOL = 'T' AND (L.MES = (EXTRACT(MONTH FROM DATEADD(-1 MONTH TO CURRENT_DATE))) AND L.ANO = 2023) GROUP BY L.ITEM) AS CONSUMO1,
--(SELECT SUM(L.QTDE) FROM GELANSAI L WHERE L.CONSOL = 'T' AND (L.MES = (EXTRACT(MONTH FROM DATEADD(-2 MONTH TO CURRENT_DATE))) AND L.ANO = 2022) GROUP BY L.ITEM) AS CONSUMO2,
--(SELECT SUM(L.QTDE) FROM GELANSAI L WHERE L.CONSOL = 'T' AND (L.MES = (EXTRACT(MONTH FROM DATEADD(-3 MONTH TO CURRENT_DATE))) AND L.ANO = 2022) GROUP BY L.ITEM) AS CONSUMO3,
C.MES,
C.ANO,
L.ITEM,
I.NOME,
I.UNI_CON,
I.CONVER,
I.UNI_COMP,
MAX(I.EST_MAX) EST_MAXIMO,
MAX(I.CUSTO) PRECO,
MAX(EST_MIN) EST_MINIMO,
MAX(I.ESTOQUE) ESTOQUE,
SUM(L.QTDE) QUANTIDADE
FROM GECADSAI C INNER JOIN GELANSAI L ON C.ANO = L.ANO AND C.MES = L.MES AND C.DOC = L.DOC
LEFT JOIN GEITENS I ON L.ITEM = I.COD
WHERE (((C.MES = (EXTRACT(MONTH FROM DATEADD(-1 MONTH TO CURRENT_DATE))) AND C.ANO = 2023 ))
OR ((C.MES = (EXTRACT(MONTH FROM DATEADD(-2 MONTH TO CURRENT_DATE)))) AND C.ANO = 2022)
OR (C.MES = (EXTRACT(MONTH FROM DATEADD(-3 MONTH TO CURRENT_DATE))) AND C.ANO = 2022))
AND C.CDC NOT BETWEEN 9901 AND 9999
AND I.REF = 1
AND L.CONSOL = 'T'
AND C.CONSOL = 'T'
GROUP BY L.ITEM, I.NOME, C.ANO, C.MES, I.UNI_CON, I.VLRMED, I.UNI_COMP, I.CONVER
Related
Right now my code works, but it is not dynamic. Below shows the sum of daily values from a daily table in January 2022 compared to the monthly value from the monthly table for January 2022.
I am trying to figure out how to code this so the daily totals compared to the monthly can be pulled at anytime and I won't have to change the dates in the WHERE clauses everytime.
SELECT
b.LocationDescription AS 'Location'
,CONVERT(varchar, cm.RecordDate, 1) AS 'Month Date'
,DATENAME(month,cm.RecordDate) AS 'Month'
,SUM(cm.Production) AS 'Monthly Prod'
,d.total AS 'Daily Prod'
,SUM(cm.Production)-d.total AS 'Diff'
,(CASE WHEN d.total = 0 THEN 0 ELSE (SUM(cm.Production) - d.total)/d.total*100 END) AS 'Percent'
FROM CompletionMonthlyTb cm
INNER JOIN CompletionTb c ON cm.SystemID = c.SystemID
INNER JOIN LocationTb as b ON c.LocationID = b.LocationSystemID
JOIN (SELECT DISTINCT
b.LocationDescription AS 'Location'
,sum(cd.[Production]) AS 'Total'
FROM [xxxxxxx].[dbo].[LocationTb] b
JOIN xxxxxxxxx.dbo.CompletionTb c ON c.LocationID = b.LocationSystemID
JOIN xxxxxxx.dbo.CompletionDailyTb cd ON cd.SystemID = c.SystemID
WHERE cd.RecordDate BETWEEN '1-1-2022' AND '1-31-22'
GROUP BY b.LocationDescription) AS d ON d.Location = b.LocationDescription
WHERE cm.RecordDate = '2022-01-01'
GROUP BY b.LocationDescription, cm.RecordDate, d.total
ORDER BY cm.RecordDate, b.LocationDescription
RESULTS:
Location Month Date Month Monthly Prod Daily Prod Diff Percent
Alpha 01/01/22 January 27663 25584 2079 8
Beta 01/01/22 January 25503 26104 -600 -2
Using SQL Server, I am trying to get the latest date a client completed an assessment that is less than the current date (or census date in this case).
This query should roll through every day of the client census, and if the client is on the census that day, their most recently completed assessment ID, the completed date, and the census date should be displayed.
I am currently trying the query below, but am still getting every assessment completed date for every day the client is on the census.
SELECT AssessmentID
,Max(CompletedDate) compdt
,cn.CensusDate
FROM [view_ods_as_assessment] ast
JOIN [dbo].[view_ods_facility_patient] fp on ast.ResidentID = fp.PatientID and ast.FacilityID = fp.FacilityID
JOIN [dbo].[view_ods_daily_census] cn on fp.PatientMRN = cn.PatientMRN and fp.FacilityID = cn.FacilityID
--JOIN [dbo].[view_ods_payer] py on cn.PayerID = py.PayerID
WHERE CensusDate between '11/01/2021' and '11/15/2021'
GROUP BY AssessmentID
,cn.CensusDate
HAVING MAX(ast.CompletedDate) < cn.CensusDate
ORDER BY CensusDate, compdt
UPDATE:
I have since changed my query, which now works but is very slow (>10 minutes).
SELECT t1.FacilityID
,t1.ResidentID
,fp.PatientMRN
,fp.LastName
,fp.FirstName
,cast(t1.AssessDate as date) AssessDate
,t1.CmiState
,cast(t2.MxDt as date) CompletedDate
,cast(t2.CensusDate as date) CensusDate
FROM [view_ods_as_assessment] t1
INNER JOIN [dbo].[view_ods_facility_patient] fp on t1.ResidentID = fp.PatientID and t1.FacilityID = fp.FacilityID
INNER JOIN (
SELECT ResidentID, ast.FacilityID, CensusDate, max(CompletedDate) AS MxDt
FROM [view_ods_as_assessment] ast
JOIN [dbo].[view_ods_facility_patient] fp on ast.ResidentID = fp.PatientID and ast.FacilityID = fp.FacilityID
JOIN [dbo].[view_ods_daily_census] cn on fp.PatientMRN = cn.PatientMRN and fp.FacilityID = cn.FacilityID
WHERE ast.FacilityID = '12'
and IsDeleted = 'N'
and CompletedDate IS NOT NULL
and CmiState IS NOT NULL
and StrikeoutFlag = 'N'
and SubmissionReq = 'Y'
and Status = 'Accepted'
and CompletedDate < CensusDate
and CensusDate between '12/01/2021' and '12/12/2021'
GROUP BY ResidentID, ast.FacilityID, CensusDate
) t2 ON t1.ResidentID = t2.ResidentID AND t1.FacilityID = t2.FacilityID and t1.CompletedDate = t2.MxDt
WHERE t1.FacilityID = '12'
and IsDeleted = 'N'
and CompletedDate IS NOT NULL
and CmiState IS NOT NULL
and StrikeoutFlag = 'N'
and SubmissionReq = 'Y'
and Status = 'Accepted'
Sample:
AssessmentID
compdt
1
2/1/2021
2
3/1/2021
3
8/1/2021
4
12/1/2021
Desired:
AssessmentID
compdt
CensusDate
2
3/1/2021
6/1/2021
3
8/1/2021
11/1/2021
3
8/1/2021
12/1/2021
4
12/1/2021
12/2/2021
SELECT
DATEPART(YEAR, tblGRN.GRNApproveDate) AS Year,
tblGRNMaterials.MaterialCode,
tblMaterial.MaterialDescription,
SUM(tblGRNMaterials.NetQty) AS Qty
FROM
tblGRN
INNER JOIN
tblGRNMaterials ON tblGRN.GRNNO = tblGRNMaterials.GRNNO
INNER JOIN
tblMaterial ON tblGRNMaterials.MaterialCode = tblMaterial.MaterialCode
WHERE
(tblGRN.GRNStoreID = 'RM_Main')
AND (tblGRN.GRNStatus = 1)
AND (CONVERT(DATE, tblGRN.GRNApproveDate) BETWEEN '2017-01-01' AND '2018-12-31')
GROUP BY
tblGRNMaterials.MaterialCode, tblMaterial.MaterialDescription,
DATEPART(YEAR, tblGRN.GRNApproveDate)
ORDER BY
tblGRNMaterials.MaterialCode
My output
Year MaterialCode MaterialDescription Qty
-------------------------------------------------------------
2017 LM/CCM/SO Cellulose C. Methyl 200.000
2018 LM/CCM/SO Cellulose C. Methyl 350.000
2017 LM/MAG/PW Magnesium Stearate 175.000
2018 LM/MAG/PW Magnesium Stearate 250.000
2017 LM/MCC/PW Micro Crystal Cellulose 75.000
2018 LM/MCC/PW Micro Crystal Cellulose 0.320
I need to select each year holding the maximum value of 'Qty', comparison with year 2017 and 2018
Result should be:
Year MaterialCode MaterialDescription Qty
----------------------------------------------------------
2018 LM/CCM/SO Cellulose C. Methyl 350.000
2018 LM/MAG/PW Magnesium Stearate 250.000
2017 LM/MCC/PW Micro Crystal Cellulose 75.000
First, I would write the query like this:
SELECT year(g.GRNApproveDate) AS Year, gm.MaterialCode,
m.MaterialDescription, SUM(gm.NetQty) AS Qty
FROM tblGRN g INNER JOIN
tblGRNMaterials gm
ON g.GRNNO = gm.GRNNO INNER JOIN
tblMaterial m
ON gm.MaterialCode = m.MaterialCode
WHERE g.GRNStoreID = 'RM_Main' AND
g.GRNStatus = 1 AND
g.GRNApproveDate >= '2017-01-01' AND
g.GRNApproveDate < '2019-01-01'
GROUP BY gm.MaterialCode, m.MaterialDescription, year(g.GRNApproveDate)
ORDER BY gm.MaterialCode;
Although not the most performant method, probably the simplest is:
SELECT TOP (1) WITH TIES, year(g.GRNApproveDate) AS Year, gm.MaterialCode,
m.MaterialDescription, SUM(gm.NetQty) AS Qty
FROM tblGRN g INNER JOIN
tblGRNMaterials gm
ON g.GRNNO = gm.GRNNO INNER JOIN
tblMaterial m
ON gm.MaterialCode = m.MaterialCode
WHERE g.GRNStoreID = 'RM_Main' AND
g.GRNStatus = 1 AND
g.GRNApproveDate >= '2017-01-01' AND
g.GRNApproveDate < '2019-01-01'
GROUP BY gm.MaterialCode, m.MaterialDescription, year(g.GRNApproveDate)
ORDER BY ROW_NUMBER() OVER (PARTITION BY gm.MaterialCode ORDER BY SUM(gm.NetQty) DESC);
In my SQL query, I need to do an alias based arithmetic on alias that is located within a nested select.
My query look like this:
SELECT P.EMPLOYEE_NO, EE.BASIC_SALARY,
(SELECT SUM (NEW_ACTIVITY_VALUE)
FROM
(SELECT
(CASE WHEN P.ACTIVITY_TYPE = '0' THEN (P.ACTIVITY_VALUE * (-1))
ELSE P.ACTIVITY_VALUE
END) AS NEW_ACTIVITY_VALUE
FROM V_EMPLOYEE_PAYACT P
WHERE P.ACTIVITY_TYPE IN ('0','1') AND P.EMPLOYEE_NO = '00002789' AND
((YEAR = 2014 AND MONTH <= 4)
OR
(YEAR > 2013 AND YEAR <2014)
OR
(YEAR = 2013 AND MONTH >= 5))
) t
) AS SUM_ACTIVITY_VALUE,
(SELECT NEW_BASIC_SALARY FROM
(SELECT (EE.BASIC_SALARY- SUM_ACTIVITY_VALUE) AS NEW_BASIC_SALARY
FROM EMPLOYEE_EMPLOYMENT EE
) AS X
FROM EMPLOYEE_EMPLOYMENT EE
JOIN V_EMPLOYEE_PAYACT P
ON EE.EMPLOYEE_ID = P.EMPLOYEE_ID
WHERE P.EMPLOYEE_NO = '00002789'
GROUP BY P.EMPLOYEE_NO, EE.BASIC_SALARY
The only problem that I'm having now is at this part:
..(SELECT NEW_BASIC_SALARY FROM
(SELECT (EE.BASIC_SALARY- SUM_ACTIVITY_VALUE) AS NEW_BASIC_SALARY
FROM EMPLOYEE_EMPLOYMENT EE
) AS X...
If I deduct the above problematic part from the query, I got a result that looks like this:
EMP_NO |s BASIC_SALARY|s SUM_ACTIVITY_VALUE|s
1234-s-s-s| 2009-s-s-s-s-s-s-s| 100-s-s-s-s-s-s-s-s-s|
What I need my result looks like is:
EMP_NO |s BASIC_SALARY|s SUM_ACTIVITY_VALUE|s NEW_BASIC_SALARY|s
1234-s-s-s| 2009-s-s-s-s-s-s-s| 100-s-s-s-s-s-s-s-s-s-s-s| 1909-s-s-s-s-s-s-s|
P/S: I am very sorry for my question formatting, kinda lost at how to format a table.
There might be other flaws in your query, but if you're getting the values you want to subtract with your functioning query, than you can simply make that whole thing a subquery and do the subtraction outside of it, using the aliases:
SELECT *,BASIC_SALARY - SUM_ACTIVITY_VALUE as NEW_BASIC_SALARY
FROM (
SELECT P.EMPLOYEE_NO
, EE.BASIC_SALARY
,(SELECT SUM (NEW_ACTIVITY_VALUE)
FROM (SELECT (CASE WHEN P.ACTIVITY_TYPE = '0'
THEN (P.ACTIVITY_VALUE * (-1))
ELSE P.ACTIVITY_VALUE
END) AS NEW_ACTIVITY_VALUE
FROM V_EMPLOYEE_PAYACT P
WHERE P.ACTIVITY_TYPE IN ('0','1')
AND P.EMPLOYEE_NO = '00002789'
AND ((YEAR = 2014 AND MONTH <= 4)
OR (YEAR > 2013 AND YEAR <2014)
OR (YEAR = 2013 AND MONTH >= 5))
) t
) AS SUM_ACTIVITY_VALUE
FROM EMPLOYEE_EMPLOYMENT EE
JOIN V_EMPLOYEE_PAYACT P
ON EE.EMPLOYEE_ID = P.EMPLOYEE_ID
WHERE P.EMPLOYEE_NO = '00002789'
GROUP BY P.EMPLOYEE_NO, EE.BASIC_SALARY
) sub
I am using DB2 Syntax and hoping to use a UNION to create an additional row to show the rolled up values.
Rather than doing that the first portion of the union is merely naming the columns, whereas the data from the second union appears.
Here is the first portion
SELECT 'DRIVER ID' AS DRIVER_ID, 'NAME' AS NAME, 'PUNIT' AS PUNIT, 'PHONE' AS PHONE, 1767 AS TERMINAL_NUMBER, 'DRIVER TYPE' AS DRIVER_TYPE,
COALESCE((SELECT ROUND(DEC(SUM(CASE WHEN UPDATED_BY IN ('VISTAR','TM4WIN') THEN 1.00 ELSE 0.00 END))/COUNT(UPDATED_BY),2) FROM ODRSTAT, TLORDER L, DRIVER D WHERE DETAIL_LINE_ID = ORDER_ID AND STATUS_CODE IN ('ARRV#SHIP', 'ARRV#CONS', 'DEPT#SHIP', 'DEPT#CONS')
AND CURRENT_STATUS IN ('EDIBILLED','BILLD') AND L.PICK_UP_DRIVER = D.DRIVER_ID AND
D.TERMINAL_NUMBER IN (SELECT UNIQUE FIRST_FIELD_INSERT FROM SITE WHERE FAX_PHONE_NUMBER = :DIVISION) AND BILL_DATE BETWEEN CURRENT DATE - 1 MONTH AND CURRENT DATE AND ACTUAL_DELIVERY > ACTUAL_PICKUP +30 SECONDS),0) AVG_STATUS_UPDATE,
ROUND(((SELECT MAX(ODOMETER)-MIN(ODOMETER) FROM ODOHIST O
WHERE READINGDATE >= CURRENT DATE - 30 DAYS AND O.UNIT_ID IN (SELECT UNIT_ID FROM PUNIT WHERE ACTIVE_WHERE = 'D' AND FLEET_ID IN (SELECT UNIQUE USER5 FROM SITE WHERE FAX_PHONE_NUMBER = :DIVISION)))
/(SELECT NULLIF(SUM(T2.VOL_PFUEL),0) FROM FC_POS T2 INNER JOIN DRIVER D ON T2.DRIVER_ID = D.DRIVER_ID
WHERE D.TERMINAL_NUMBER IN (SELECT UNIQUE FIRST_FIELD_INSERT FROM SITE WHERE FAX_PHONE_NUMBER = :DIVISION) AND POS_DATE >= CURRENT DATE - 30 DAYS)),2) AVG_MPG,
(SELECT ROUND(AVG(TIMES),2) FROM (SELECT DELIVERY_DRIVER, ROUND(AVG(DEC((DAYS(CHECKIN_DATE) - DAYS(ACTUAL_DELIVERY)) *24 + (HOUR(CHECKIN_DATE) - HOUR(ACTUAL_DELIVERY)))/24),2) TIMES
FROM LIST_CHECKIN_AUDIT, LYNX.TLORDER WHERE LYNX.TLORDER.BILL_NUMBER = LIST_CHECKIN_AUDIT.BILL_NUMBER AND BILL_DATE >= CURRENT TIMESTAMP - 1 MONTH
AND LYNX.TLORDER.DOCUMENT_TYPE = 'INVOICE' AND ACTUAL_DELIVERY < CHECKIN_DATE AND ACTUAL_DELIVERY BETWEEN CURRENT TIMESTAMP - 6 MONTHS AND CURRENT TIMESTAMP + 3 DAYS
GROUP BY LYNX.TLORDER.BILL_NUMBER, DELIVERY_DRIVER) AVERAGES WHERE AVERAGES.DELIVERY_DRIVER IN (SELECT DRIVER_ID FROM DRIVER WHERE ACTIVE_IN_DISP = 'True' AND TERMINAL_NUMBER IN (SELECT UNIQUE FIRST_FIELD_INSERT FROM SITE WHERE FAX_PHONE_NUMBER = :DIVISION))) AS AVG_DAYS_TO_SCAN,
CAST(SUM(CASE WHEN VARCHAR(COALESCE((SELECT DATA FROM CUSTOM_DATA WHERE SRC_TABLE_KEY = DRIVER_ID AND CUSTDEF_ID = '50'),'False' ),10) = 'True' THEN 1 ELSE 0 END) AS VARCHAR(10)) AS DRIVE_AXLE,
(SELECT COUNT(UNIQUE A.BILL_NUMBER) FROM LIST_CHECKIN_AUDIT A INNER JOIN TLORDER T ON T.BILL_NUMBER = A.BILL_NUMBER
WHERE CURRENT_STATUS IN ('EDIBILLED','BILLD') AND COALESCE(PICK_UP_DRIVER,DELIVERY_DRIVER) IN (SELECT DRIVER_ID FROM DRIVER WHERE ACTIVE_IN_DISP = 'True'
AND TERMINAL_NUMBER IN (SELECT UNIQUE FIRST_FIELD_INSERT FROM SITE WHERE FAX_PHONE_NUMBER = :DIVISION)) AND BILL_DATE >= CURRENT DATE - 1 MONTH AND A.DOCUMENT_TYPE = 'DABL') AS DRIVERAXLE_SUBMISSIONS
FROM DRIVER WHERE ACTIVE_IN_DISP = 'True'
AND TERMINAL_NUMBER IN (SELECT UNIQUE FIRST_FIELD_INSERT FROM SITE WHERE FAX_PHONE_NUMBER = :DIVISION)
UNION ALL
SELECT DRIVER_ID, NAME, DEFAULT_PUNIT AS PUNIT, VARCHAR(USER9,12) AS PHONE, TERMINAL_NUMBER, DRIVER_TYPE,
COALESCE((SELECT ROUND(DEC(SUM(CASE WHEN UPDATED_BY IN ('VISTAR','TM4WIN') THEN 1.00 ELSE 0.00 END))/COUNT(UPDATED_BY),2) FROM ODRSTAT, TLORDER L WHERE DETAIL_LINE_ID = ORDER_ID AND STATUS_CODE IN ('ARRV#SHIP', 'ARRV#CONS', 'DEPT#SHIP', 'DEPT#CONS')
AND CURRENT_STATUS IN ('EDIBILLED','BILLD') AND L.PICK_UP_DRIVER = DRIVER_ID AND BILL_DATE BETWEEN CURRENT DATE - 1 MONTH AND CURRENT DATE AND ACTUAL_DELIVERY > ACTUAL_PICKUP +30 SECONDS),0) AS STATUS_UPDATE_PERCENT,
ROUND(((SELECT MAX(ODOMETER)-MIN(ODOMETER) FROM ODOHIST O
WHERE READINGDATE >= CURRENT DATE - 30 DAYS AND O.UNIT_ID = DEFAULT_PUNIT)/(SELECT NULLIF(SUM(T2.VOL_PFUEL),0) FROM FC_POS T2 WHERE T2.DRIVER_ID = DRIVER.DRIVER_ID AND POS_DATE >= CURRENT DATE - 30 DAYS)),2) AS MPG_30DAYS,
(SELECT ROUND(AVG(TIMES),2) FROM (SELECT DELIVERY_DRIVER, ROUND(AVG(DEC((DAYS(CHECKIN_DATE) - DAYS(ACTUAL_DELIVERY)) *24 + (HOUR(CHECKIN_DATE) - HOUR(ACTUAL_DELIVERY)))/24),2) TIMES
FROM LIST_CHECKIN_AUDIT, LYNX.TLORDER WHERE LYNX.TLORDER.BILL_NUMBER = LIST_CHECKIN_AUDIT.BILL_NUMBER AND BILL_DATE >= CURRENT TIMESTAMP - 1 MONTH
AND LYNX.TLORDER.DOCUMENT_TYPE = 'INVOICE' AND ACTUAL_DELIVERY < CHECKIN_DATE AND ACTUAL_DELIVERY BETWEEN CURRENT TIMESTAMP - 6 MONTHS AND CURRENT TIMESTAMP + 3 DAYS
GROUP BY LYNX.TLORDER.BILL_NUMBER, DELIVERY_DRIVER) AVERAGES WHERE AVERAGES.DELIVERY_DRIVER = DRIVER.DRIVER_ID)
AVG_DAYS_TO_SCAN,
VARCHAR(COALESCE((SELECT DATA FROM CUSTOM_DATA WHERE SRC_TABLE_KEY = DRIVER_ID AND CUSTDEF_ID = '50'),'False' ),10) AS DRIVEAXLE,
(SELECT COUNT(UNIQUE A.BILL_NUMBER) FROM LIST_CHECKIN_AUDIT A INNER JOIN TLORDER T ON T.BILL_NUMBER = A.BILL_NUMBER
WHERE CURRENT_STATUS IN ('EDIBILLED','BILLD') AND COALESCE(PICK_UP_DRIVER,DELIVERY_DRIVER) = DRIVER_ID AND BILL_DATE >= CURRENT DATE - 1 MONTH AND A.DOCUMENT_TYPE = 'DABL') AS DRIVERAXLE_SUBMISSIONS_1_MONTH
FROM DRIVER WHERE ACTIVE_IN_DISP = 'True'
AND TERMINAL_NUMBER IN (SELECT UNIQUE FIRST_FIELD_INSERT FROM SITE WHERE FAX_PHONE_NUMBER = :DIVISION)
I've not looked at your code...given the lack of formatting, it's not easy to follow.
However, when I've used UNION in the past to provide rolled up values, I've included extra columns that provides a way for me to differentiate between details and totals. These extra columns is also used as the first column to ORDER BY
Example:
select
digits(HCUSNR) as Cust_Num,
CCUSNM,
char(HINVNR),
hinamt,
-- Control fields
' ' concat digits(HCMPCL),
case
when HTRCDE in ('A', 'E', 'R')
then ' LVL3'
else ' LVL1'
end,
HCUSNR, DDVDSC, HDIVSN
UNION ALL
select
' ',
'Daily Invoice Total',
' ',
sum(hinamt),
-- Control Fields
' ' concat digits(HCMPCL), ' LVL2', 0, ' ', HDIVSN
group by
HDIVSN, HCMPCL
--Following order by applies to entire results set
order by 5,6,7,8,9
But the above was written close to 20 years ago...
If I needed to do it today, I'd use the grouping sets, rollup, and cube functionality that IBM has added to the DB.
What platform and version of DB2 are you using? Are grouping sets, rollup and/or cube an option?