I have a query
SELECT
ZEML.ICC_CODE AS ICC_CODE
,SUM(CS.TOT_HOURS) AS TOT_HOURS
,SUM(CS.NUM_INCIDENT_ALL) AS NUM_INCIDENTS
,(VALUE(FLOAT(SUM(CS.NUM_INCIDENT_ALL)) * 200000 / SUM(TOT_HOURS)
,0)) AS INC_RATE
FROM TR.CLAIMS_SUMM CS
INNER JOIN TR.LOCATION_MASTER LM
ON LM.LOCATION = CS.LOCATION
AND CS.LOCATION < '900'
LEFT JOIN TR.LOCATION_ASSIGNMENTS DISTRICT
ON DISTRICT.LOCATION = LM.LOCATION
AND DISTRICT.ASSIGNMENT_TYPE = 'District'
LEFT JOIN TR.LOCATION_ASSIGNMENTS TERRITORY
ON TERRITORY.LOCATION = LM.LOCATION
AND TERRITORY.ASSIGNMENT_TYPE = 'Territory'
LEFT JOIN TR.EMPL_CLAIMS ZEML
ON CS.LOCATION = ZEML.LOCATION
AND ZEML.TYPE = 'WC'
AND ZEML.STATUS <> 'V'
AND ZEML.CLAIM_ACTION NOT IN ('D','F','I','H')
WHERE CS.DW_DATE BETWEEN '01/01/2014'
AND '05/31/2014'
AND (MONTH(ZEML.DATE_OF_INCIDENT) = MONTH(CS.DW_DATE)
AND YEAR(ZEML.DATE_OF_INCIDENT) = YEAR(CS.DW_DATE))
GROUP BY ZEML.ICC_CODE
UNION
SELECT
'OTHER' AS ICC_CODE
, 0 AS TOT_HOURS
, 0 AS NUM_INCIDENTS
, 0 AS INC_RATE
FROM SYSIBM.SYSDUMMY1
WHERE 1 = 1
ORDER BY 1
in my union where I made an other I want to select everything else from the tr.empl_claims table and store it in the other from the union because this is what I have many other ICC codes without incidents on them and I am doing calculations on our incident rate and hourse based off of all the data but my query right now is only selecting the ones that currently is having incidents which is throwing off my calculations.
From your use of FROM SYSIBM.SYSDUMMY1 I believe you are using DB2 database. If yes, you can use CTE (common table expression) to achieve the desired result like
WITH cte1 AS
(
SELECT
ZEML.ICC_CODE AS ICC_CODE
,SUM(CS.TOT_HOURS) AS TOT_HOURS
,SUM(CS.NUM_INCIDENT_ALL) AS NUM_INCIDENTS
,(VALUE(FLOAT(SUM(CS.NUM_INCIDENT_ALL)) * 200000 / SUM(TOT_HOURS)
,0)) AS INC_RATE
FROM TR.CLAIMS_SUMM CS
... <rest of the code> ...
)
select * from cte1
UNION ALL
SELECT
ICC_CODE
, 0 AS TOT_HOURS
, 0 AS NUM_INCIDENTS
, 0 AS INC_RATE
FROM TR.EMPL_CLAIMS
WHERE ICC_CODE NOT IN
(
SELECT distinct ICC_CODE
FROM cte1
)
ORDER BY 1
SideNote: You are joining the same table LOCATION_ASSIGNMENTS twice (as below) which is not needed.
LEFT JOIN TR.LOCATION_ASSIGNMENTS DISTRICT
ON DISTRICT.LOCATION = LM.LOCATION
AND DISTRICT.ASSIGNMENT_TYPE = 'District'
LEFT JOIN TR.LOCATION_ASSIGNMENTS TERRITORY
ON TERRITORY.LOCATION = LM.LOCATION
AND TERRITORY.ASSIGNMENT_TYPE = 'Territory'
This can be transformed to below using a IN operator
LEFT JOIN TR.LOCATION_ASSIGNMENTS DISTRICT
ON DISTRICT.LOCATION = LM.LOCATION
AND DISTRICT.ASSIGNMENT_TYPE IN ('District', 'Territory')
See more about Common Table Expression in DB2 Here.
Hope this helps.
Related
I have created an ABAP CDS view using ACDOCA, BSID, MARA, MAKT and such tables.
Now my CDS view contains list of customers along with their outstanding (FI) documents.
Against these customers, FI documents and certain more parameters, I am maintaining certain data in a custom table.
Now using left outer join I want to connect this CDS view with custom table.
The problem now is that this join is working like inner join, so if my custom table is blank my output is displaying without values whereas it should be displaying CDS view as it is, and custom table fields as blank.
Now based on similar issues on web I did research and found some useful points:
all conditions on right table are included at most in ON join condition
tried to include null values from right side custom table as well.
tried using just one parameter on join condition to see the result (still working as inner join)
Here is my complete select statement, where:
ZPD1 is my ABAP CDS view of ACDOCA, BSDI ... tables
ZPD_HSL is an ABAP CDS view for customer wise GL amount calculation.
ZFI_PDRATE_MAP is my custom table which contains rate for customer / FI docs combination.
What could be a misstep in this statement?
SELECT
FROM ZPD1( PBUKRS = #BUKRS-LOW ,
POSTFROM = #COL_DATE-LOW ,
POSTTO = #COL_DATE-HIGH ) AS A
LEFT OUTER JOIN ZFI_PDRATE_MAP AS F
ON A~PROD_CATEGORY = F~PROD_CATEGORY
AND A~OD_DATE GE F~POST_DT_FROM
AND A~OD_DATE LE F~POST_DT_TO
AND F~COL_DT_FROM GE #COL_DATE-LOW
AND F~COL_DT_TO LE #COL_DATE-HIGH
AND F~SALES_OFFICE = #VKBUR-LOW
AND CASE WHEN A~ARREAR_DAYS <= 0 THEN 'NOD'
WHEN A~ARREAR_DAYS > 0 THEN 'OD'
END = F~OD
INNER JOIN KNA1 AS H
ON H~KUNNR = A~KUNNR
INNER JOIN TVKBT AS I
ON I~VKBUR = F~SALES_OFFICE
AND I~SPRAS = #SY-LANGU
LEFT OUTER JOIN SKAT AS J
ON J~SAKNR = A~HKONT
AND J~SPRAS = 'E'
AND J~KTOPL = '1000'
LEFT OUTER JOIN MAKT AS K
ON K~MATNR = A~MATNR
AND K~SPRAS = 'E'
LEFT OUTER JOIN T001W AS L
ON L~WERKS = A~WERKS
FIELDS
A~RBUKRS AS BUKRS,
A~KUNNR,
H~NAME1,
F~SALES_OFFICE,
I~BEZEI,
A~BELNR AS COL_BELNR,
A~GJAHR AS COL_GJAHR,
A~HSL AS COL_AMT,
A~BUDAT AS COL_DATE,
A~KEY_DATE AS KEY_OS_DATE,
A~OD_DOC AS OS_BELNR,
A~OD_YR AS OS_GJAHR,
A~BLART ,
A~OD_DATE AS OS_DATE,
CASE WHEN A~SHKZG = 'H' THEN CAST( A~WRBTR * -1 AS CURR( 12, 2 ) )
ELSE A~WRBTR
END AS OS_AMT ,
A~DUE_DATE,
A~ARREAR_DAYS,
CASE WHEN A~ARREAR_DAYS <= 0 THEN 'NOD'
WHEN A~ARREAR_DAYS > 0 THEN 'OD'
ELSE ' '
END AS OD_IND,
A~HKONT,
J~TXT50,
A~PROD_CATEGORY,
A~MATNR,
K~MAKTX,
A~WERKS ,
L~NAME1,
A~BWTAR,
A~PROFIT_CENTRE AS PRCTR,
COALESCE( F~PD_RATE , 0 ) AS RATE,
0 AS PD_AMT,
CASE WHEN A~ARREAR_DAYS > 0 THEN
CAST(
DIVISION(
( CAST( A~WRBTR * F~PD_RATE AS CURR( 15 ,2 ) ) ) ,
100 ,
3 )
AS CURR( 15, 2 ) )
* -1
ELSE
DIVISION(
( CAST( A~WRBTR * F~PD_RATE AS CURR( 15 , 2 ) ) ) ,
100 ,
3 )
END AS ITEM_PD_AMT, "DISCOUNT_RATE,
0 AS ITEM_PD_AMT1,
A~MAIN_TYPE
WHERE A~KUNNR IN #KUNNR
AND NOT EXISTS (
SELECT *
FROM ZFI_PAYMENT_DISC
WHERE BELNR = A~BELNR
AND GJAHR = A~GJAHR
AND BUKRS = A~RBUKRS
AND SALES_OFFICE = #VKBUR-LOW
AND A~KUNNR IN #KUNNR
AND OS_BELNR EQ A~OD_DOC )
AND A~ARREAR_DAYS <= #OD
AND ( F~COL_AMT_FROM LE (
SELECT SUM( COLLECT )
FROM ZPD_HSL( BUKRS = #BUKRS-LOW ,
BUDATFROM = #COL_DATE-LOW ,
BUDATO = #COL_DATE-HIGH )
WHERE KUNNR = A~KUNNR )
AND F~COL_AMT_TO GE (
SELECT SUM( COLLECT )
FROM ZPD_HSL( BUKRS = #BUKRS-LOW ,
BUDATFROM = #COL_DATE-LOW ,
BUDATO = #COL_DATE-HIGH )
WHERE KUNNR = A~KUNNR )
)
ORDER BY A~KUNNR, A~BELNR ,A~DUE_DATE ASCENDING
INTO TABLE #PROV_POST.
This is a mere guess, as your complex setup makes it hard to reproduce a working example.
My assumption is that the INNER JOIN TVKBT AS I ON I~VKBUR = F~SALES_OFFICE is getting in the way. It inner-joins to your custom table, aliased as F, and might lead to an overreduction of records if the join order is interpreted wrong.
I'd recommend to remove that join and see whether that fixes the basic join result.
In any way, I would recommend to add parentheses and reorder the join clauses to make clear what the "left" side of the equation is, and to remove any ambiguity, both for the interpreter, and the reader.
I have a UNION of 3 tables for calculating some balance and I need to get the running SUM of that balance but I can't use PARTITION OVER, because I must do it with a sql query that can work in Access.
My problem is that I cannot use JOIN on an alias subquery, it won't work.
How can I use alias in a JOIN to get the running total?
Or any other way to get the SUM that is not with PARTITION OVER, because it does not exist in Access.
This is my code so far:
SELECT korisnik_id, imePrezime, datum, Dug, Pot, (Dug - Pot) AS Balance
FROM (
SELECT korisnik_id, k.imePrezime, r.datum, SUM(IIF(u.jedinstven = 1, r.cena, k.kvadratura * r.cena)) AS Dug, '0' AS Pot
FROM Racun r
INNER JOIN Usluge u ON r.usluga_id = u.ID
INNER JOIN Korisnik k ON r.korisnik_id = k.ID
WHERE korisnik_id = 1
AND r.zgrada_id = 1
AND r.mesec = 1
AND r.godina = 2017
GROUP BY korisnik_id, k.imePrezime, r.datum
UNION ALL
SELECT korisnik_id, k.imePrezime, rp.datum, SUM(IIF(u.jedinstven = 1, rp.cena, k.kvadratura * rp.cena)) AS Dug, '0' AS Pot
FROM RacunP rp
INNER JOIN Usluge u ON rp.usluga_id = u.ID
INNER JOIN Korisnik k ON rp.korisnik_id = k.ID
WHERE korisnik_id = 1
AND rp.zgrada_id = 1
AND rp.mesec = 1
AND rp.godina = 2017
GROUP BY korisnik_id, k.imePrezime, rp.datum
UNION ALL
SELECT uu.korisnik_id, k.imePrezime, uu.datum, '0' AS Dug, SUM(uu.iznos) AS Pot
FROM UnosUplata uu
INNER JOIN Korisnik k ON uu.korisnik_id = k.ID
WHERE korisnik_id = 1
GROUP BY uu.korisnik_id, k.imePrezime, uu.datum
) AS a
ORDER BY korisnik_id
You can save a query (let's name it Query1) for the UNION of the 3 tables and then create another query that returns each row in the first query and calculates the sum of the rows that are before it (optionally checking that they are in the same group).
It should be something like this:
SELECT *, (
SELECT SUM(Value) FROM Query1 AS b
WHERE b.GroupNumber=a.GroupNumber
AND b.Position<=a.Position
) AS RunningSum
FROM Query1 AS a
However, it's more efficient to do that in the report.
I have written a fairly simple recursive CTE statement. The purpose is that it looks up a structure and returns the top level item
Here is the code
WITH cte_BOM(parent_serial_id, serial_id, serial_batch_no, sort)
AS (SELECT BOM.parent_serial_id, BOM.serial_id, p.serial_batch_no, 1
FROM serial_status AS BOM
INNER JOIN item_serial_nos p ON BOM.parent_serial_id = p.serial_id
WHERE BOM.serial_id = '16320' AND BOM.is_current = 'Y'
UNION ALL
SELECT
BOM1.parent_serial_id, bom1.serial_id, p1.serial_batch_no, cte_BOM.sort + 1
FROM cte_BOM
INNER JOIN serial_status AS BOM1 ON cte_BOM.parent_serial_id =
BOM1.serial_id
INNER JOIN item_serial_nos p1 ON BOM1.parent_serial_id = p1.serial_id
WHERE BOM1.is_current = 'Y'
)
SELECT TOP 1
cte_BOM.*
FROM
cte_BOM
ORDER BY sort desc
As you can see I just hard code the serial_id at the moment. What I now need to accomplish is to run this cte against a subset of data. I’m now stuck on how I can do this.
So I would produce a list of serial_ids by means of another select statement, and then for each row use this serial_id in place of the ones that is currently hard coded and return the 1st record. Importantly if a serial_id has no parent that should still return a row
The second SELECT would be this:
SELECT serial_id
FROM
item_serial_nos
WHERE
item_serial_nos.item_id = '15683'
Any suggestions appreciated. (using SQL 2008 R2)
If I understand your goal correctly, you can just remove the hardcoded serial_id from the cte and add the start serial_id:
WITH cte_BOM(parent_serial_id, serial_id, serial_batch_no, sort, Original_Serial_id)
AS (
SELECT BOM.parent_serial_id
, BOM.serial_id
, p.serial_batch_no
, 1
, BOM.serial_id
FROM serial_status AS BOM
INNER JOIN item_serial_nos p
ON BOM.parent_serial_id = p.serial_id
WHERE BOM.is_current = 'Y'
UNION ALL
SELECT BOM1.parent_serial_id
, bom1.serial_id
, p1.serial_batch_no
, cte_BOM.sort + 1
, cte_BOM.Original_Serial_id
FROM cte_BOM
INNER JOIN serial_status AS BOM1
ON cte_BOM.parent_serial_id = BOM1.serial_id
INNER JOIN item_serial_nos p1
ON BOM1.parent_serial_id = p1.serial_id
WHERE BOM1.is_current = 'Y'
)
SELECT cte_BOM.*
FROM cte_BOM
INNER JOIN (
SELECT cte_BOM.Original_Serial_id
, MAX(sort) sort_max
FROM cte_BOM
WHERE cte_BOM.Original_Serial_id IN (
SELECT serial_id
FROM item_serial_nos
WHERE item_serial_nos.item_id = '15683'
)
GROUP BY cte_BOM.Original_Serial_id
) max_cte
ON max_cte.Original_Serial_id = cte_BOM.Original_Serial_id
AND max_cte.sort_max = cte_BOM.sort
The recursive CTE is only executed when it's called from the last select, so it is only executed for those records that are selected in the IN query. So you shouldn't suffer a performance hit because of this.
I have the following data
CREATE TABLE #Test
(
Severity NVARCHAR(50)
,WorkId INT
)
INSERT INTO #Test VALUES('High',1)
INSERT INTO #Test VALUES('Critical',2)
SELECT
CASE
WHEN Severity IN ('High','Critical') THEN 'Critical'
WHEN Severity IN ('Low','Medium') THEN 'Medium'
END AS 'Severity'
,COUNT(*) AS 'Total'
FROM #Test
GROUP BY
CASE
WHEN Severity IN ('High','Critical') THEN 'Critical'
WHEN Severity IN ('Low','Medium') THEN 'Medium'
END
This results in output -
Severity | Total
---------+-------
Critical | 2
I am expecting the following output -
Severity | Total
---------+-------
Critical | 2
Medium | 0
I have looked into the following two links which details a similar case but not same and am still unable to get the result -
http://ask.sqlservercentral.com/questions/47705/showing-null-values-as-well-in-group-by-in-sql.html
How to return empty groups in SQL GROUP BY clause
Any help or links?
Further update.
Having tried the solution below, the results are still not appearing. Pasting here the actual code wherein I would need to apply the logic
SELECT s.NewSeverity AS 'Severity'
,COUNT(WI.microsoft_vsts_common_severity) AS 'Total'
FROM ( VALUES
('Critical','I-High')
,('High','I-High')
,('Medium','I-Low')
,('Low','I-Low')
)s(OldSeverity,NewSeverity)
LEFT JOIN DimWorkItem WI (NOLOCK)
ON WI.microsoft_vsts_common_severity = s.OldSeverity
JOIN dbo.DimPerson P
ON p.personsk = WI.system_assignedto__personsk
JOIN DimTeamProject TP
ON WI.TeamProjectSK = TP.ProjectNodeSK
JOIN DimIteration Itr (NOLOCK)
ON Itr.IterationSK = WI.IterationSK
JOIN DimArea Ar (NOLOCK)
ON Ar.AreaSK = WI.AreaSK
WHERE TP.ProjectNodeName = 'ABC'
AND WI.System_WorkItemType = 'Bug'
AND WI.Microsoft_VSTS_CMMI_RootCause <> 'Change Request'
AND Itr.IterationPath LIKE '%\ABC\R1234\Test\IT%'
AND WI.System_State NOT IN ( 'Rejected', 'Closed' )
AND WI.System_RevisedDate = CONVERT(datetime, '9999', 126)
GROUP BY s.NewSeverity
In actual there are only two 'Low' items, hence the output I am getting is I-Low, 2 whereas I want even I-High to appear with 0 count.
The way I would go about this is to create your own table of values using a table value constructor:
SELECT OldSeverity, NewSeverity
FROM (VALUES
('Critical', 'Critical'),
('High', 'Critical'),
('Medium', 'Medium'),
('Low', 'Medium')
) s (OldSeverity, NewSeverity);
This gives a table you can select from, then left join to your existing table:
SELECT Severity = s.NewSeverity,
Total = COUNT(t.Severity)
FROM (VALUES
('Critical', 'Critical'),
('High', 'Critical'),
('Medium', 'Medium'),
('Low', 'Medium')
) s (OldSeverity, NewSeverity)
LEFT JOIN #Test t
ON t.Severity = s.OldSeverity
GROUP BY s.NewSeverity;
This will give the desired results.
Example on SQL Fiddle
EDIT
The problem you have with the way that you are implimenting the query, is that although you have immediately left joined to DimWorkItem you then inner join to subsequent tables and refer to columns in WorkItem in the where clause, which undoes your left join and turns it back into an inner join. You need to place your whole logic into a subquery, and left join to this:
SELECT s.NewSeverity AS 'Severity'
,COUNT(WI.microsoft_vsts_common_severity) AS 'Total'
FROM ( VALUES
('Critical','I-High')
,('High','I-High')
,('Medium','I-Low')
,('Low','I-Low')
)s(OldSeverity,NewSeverity)
LEFT JOIN
( SELECT wi.Severity
FROM DimWorkItem WI (NOLOCK)
JOIN dbo.DimPerson P
ON p.personsk = WI.system_assignedto__personsk
JOIN DimTeamProject TP
ON WI.TeamProjectSK = TP.ProjectNodeSK
JOIN DimIteration Itr (NOLOCK)
ON Itr.IterationSK = WI.IterationSK
JOIN DimArea Ar (NOLOCK)
ON Ar.AreaSK = WI.AreaSK
WHERE TP.ProjectNodeName = 'ABC'
AND WI.System_WorkItemType = 'Bug'
AND WI.Microsoft_VSTS_CMMI_RootCause <> 'Change Request'
AND Itr.IterationPath LIKE '%\ABC\R1234\Test\IT%'
AND WI.System_State NOT IN ( 'Rejected', 'Closed' )
AND WI.System_RevisedDate = CONVERT(datetime, '9999', 126)
) WI
ON WI.Severity = s.OldSeverity
GROUP BY s.NewSeverity;
SELECT pv.PropertyID, COUNT(pv.VisitID) AS InitialVisit
FROM tblPAppointments pa INNER JOIN tblPropertyVisit pv ON pv.AppID = pa.AppID
WHERE pv.Status = 0
GROUP BY pv.PropertyID
UNION ALL
SELECT jv.PropertyID, COUNT(jv.JobVistID) AS JobVisit
FROM tblPAppointments pa INNER JOIN tblJobVisits jv ON jv.AppID = pa.AppID
WHERE jv.VisitStatus = 1
GROUP BY jv.PropertyID
I need to get InitialVisit count and JobVisit count in two separate columns.above query returns just two columns (PropertyID,InitialVisit).
Use a NULL as a placeholder for the column that there won't be any output for:
SELECT pv.PropertyID,
COUNT(pv.VisitID) AS InitialVisit,
NULL AS jobvisit
FROM tblPAppointments pa
JOIN tblPropertyVisit pv ON pv.AppID = pa.AppID
WHERE pv.Status = 0
GROUP BY pv.PropertyID
UNION ALL
SELECT jv.PropertyID,
NULL AS initialvisit,
COUNT(jv.JobVistID) AS JobVisit
FROM tblPAppointments pa
JOIN tblJobVisits jv ON jv.AppID = pa.AppID
WHERE jv.VisitStatus = 1
GROUP BY jv.PropertyID
This will return three columns. The column alias is necessary in the first query, but not in the second -- I aliased both to make it clear what is happening.
Be aware that using NULL like this in SQL Server will require you to use CAST/CONVERT on the NULL for data types other than INT because SQL Server defaults the NULL to an INT data type (as odd as that is).
An alternate query that doesn't use UNION:
SELECT x.propertyid,
COUNT(y.visitid) AS initialvisit,
COUNT(z.jobvisitid) AS jobvisit
FROM (SELECT pv.propertyid
FROM TBLPROPERTYVISIT pv
WHERE EXISTS (SELECT NULL
FROM TBLAPPOINTMENTS a
WHERE a.appid = pv.appid)
UNION
SELECT jv.propertyid
FROM TBLJOBVISIT jv
WHERE EXISTS (SELECT NULL
FROM TBLAPPOINTMENTS a
WHERE a.appid = jv.appid)) x
LEFT JOIN TBLPROPERTYVISIT y ON y.propertyid = x.propertyid
LEFT JOIN TBLJOBVISIT z ON z.propertyid = x.propertyid
GROUP BY x.propertyid
No need for a UNION at all. And you don't use tblPAppointments either
Edited to allow for no rows in one of the tables. Still one row output though
SELECT
ISNULL(pv2.PropertyID, jv2.PropertyID),
ISNULL(pv2.InitialVisit, 0),
ISNULL(jv2.JobVisit, 0)
FROM
(
SELECT pv.PropertyID, COUNT(pv.VisitID) AS InitialVisit
FROM tblPropertyVisit pv
WHERE pv.Status = 0
GROUP BY pv.PropertyID
) pv2
FULL OUTER JOIN
(
SELECT jv.PropertyID, COUNT(jv.JobVistID) AS JobVisit
FROM tblJobVisits jv
WHERE jv.VisitStatus = 1
GROUP BY jv.PropertyID
) jv2 ON pv2.PropertyID = jv2.PropertyID