I'm trying to develop a query and i got something like this
SELECT a.No,
a.Finish,
a.Shift,
a.McCode,
d.NAME,
b.ItemCode,
b.ItemName,
b.Qty,
b.LotNo,
b.Description,
CASE
WHEN b.Description LIKE '%not good%' THEN 'NG'
ELSE 'OK'
END AS OKNG,
c.ItemCode AS matcode,
c.LotNo AS matlot,
CASE
WHEN e.GroupName = 'CONTACT' THEN 'CONTACT'
ELSE 'Coil/Silver/Wire'
END AS GroupName,
( c.Qty / ( a.Qty + a.QtyNg ) ) * b.Qty AS materialused
FROM PPRDDLV a
LEFT JOIN ICMUTTRAN b
ON a.PrdNo = b.TranNo
AND a.No = b.TranId
LEFT JOIN ICMUTTRAN c
ON a.PrdNo = c.TranNo
AND a.Finish = c.DatePost
AND c.TranTypeID = 6
AND c.LotNo <> '0'
LEFT JOIN popr d
ON a.OprCode = d.Code
LEFT JOIN ICITEM e
ON c.ItemId = e.id
WHERE c.qty IS NOT NULL
AND b.ItemCode IS NOT NULL
I got around 49000 records in around 2 seconds, then I wan't to pivot a column that has 2 kind of value, so I turned it to something like this
SELECT no,
finish,
shift,
mccode,
NAME,
itemcode,
itemname,
qty,
lotno,
description,
okng,
matcode,
matlot
FROM (SELECT a.No,
a.Finish,
a.Shift,
a.McCode,
d.NAME,
b.ItemCode,
b.ItemName,
b.Qty,
b.LotNo,
b.Description,
CASE
WHEN b.Description LIKE '%not good%' THEN 'NG'
ELSE 'OK'
END AS OKNG,
c.ItemCode AS matcode,
c.LotNo AS matlot,
CASE
WHEN e.GroupName = 'CONTACT' THEN 'CONTACT'
ELSE 'Coil/Silver/Wire'
END AS GroupName,
( c.Qty / ( a.Qty + a.QtyNg ) ) * b.Qty AS materialused
FROM PPRDDLV a
LEFT JOIN ICMUTTRAN b
ON a.PrdNo = b.TranNo
AND a.No = b.TranId
LEFT JOIN ICMUTTRAN c
ON a.PrdNo = c.TranNo
AND a.Finish = c.DatePost
AND c.TranTypeID = 6
AND c.LotNo <> '0'
LEFT JOIN popr d
ON a.OprCode = d.Code
LEFT JOIN ICITEM e
ON c.ItemId = e.id
WHERE c.qty IS NOT NULL
AND b.ItemCode IS NOT NULL) AS a
PIVOT (Max(materialused)
FOR groupname IN ([CONTACT],
[Coil/Silver/Wire])) AS b
but the query won't complete even after 10 minutes, it won't even show a single records. beside that one, the first query before I used pivot, I put an order by a.no but when I executed it, the result only shows to record 105 but the query is still working and no more record was loaded.
can anyone help me find out what's going on?
thank you!
Here's the sample data collected from the inner query and the expected value after the query.
enter image description here
I realize that I selected "matcode" in the outer select while it shouldn't be there (still didn't work though, and note for the column "material used", I'll be using it later after the pivot is done)
Try using conditional aggregate instead of pivot.
SELECT no,
finish,
shift,
mccode,
NAME,
itemcode,
itemname,
qty,
lotno,
description,
okng,
matcode,
matlot,
[CONTACT] = Max(CASE WHEN GroupName = 'CONTACT' THEN materialused END),
[Coil/Silver/Wire] = Max(CASE WHEN GroupName <> 'CONTACT' THEN materialused END)
FROM (<inner query>) AS a
GROUP BY no,
finish,
shift,
mccode,
NAME,
itemcode,
itemname,
qty,
lotno,
description,
okng,
matcode,
matlot
---IF you don't have index on filter columns then try to apply for performance
SELECT a.No,
a.Finish,
a.Shift,
a.McCode,
d.NAME,
b.ItemCode,
b.ItemName,
b.Qty,
b.LotNo,
b.Description,
CASE WHEN b.Description LIKE '%not good%' THEN 'NG'
ELSE 'OK'
END AS OKNG,
c.ItemCode,
c.LotNo,
MAX(CASE WHEN e.groupname ='CONTACT' THEN ( c.Qty / ( a.Qty + a.QtyNg ) ) * b.Qty END)OVER(ORDER BY a.no) AS [CONTACT],
MAX(CASE WHEN e.groupname ='Coil/Silver/Wire' THEN ( c.Qty / ( a.Qty + a.QtyNg ) ) * b.Qty END)OVER(ORDER BY a.no) AS [Coil/Silver/Wire]
FROM PPRDDLV a WITH(NOLOCK)
LEFT JOIN ICMUTTRAN b WITH(NOLOCK)
ON a.PrdNo = b.TranNo
AND a.No = b.TranId
LEFT JOIN ICMUTTRAN c WITH(NOLOCK)
ON a.PrdNo = c.TranNo
AND a.Finish = c.DatePost
AND c.TranTypeID = 6
AND c.LotNo <> '0'
LEFT JOIN popr d WITH(NOLOCK)
ON a.OprCode = d.Code
LEFT JOIN ICITEM e
ON c.ItemId = e.id
WHERE c.qty IS NOT NULL
AND b.ItemCode IS NOT NULL
Related
WITH c AS
(SELECT A.QuestionHdrKey AS QuestionHdrKey1,
A.DivisionKey AS DivisionKey1,
COUNT(1) AS QCount
FROM Mobile.QuestionLocationMap A WITH (NOLOCK)
INNER JOIN Mobile.Question b WITH (NOLOCK) ON A.QuestionKey = b.PKey
WHERE A.QuestionHdrKey = 200305685377000000
GROUP BY A.QuestionHdrKey,
A.DivisionKey),
d AS
(SELECT a.QuestionHdrKey,
a.QuestionKey,
a.DivisionKey,
a.InvDate,
a.HdrKey,
ROW_NUMBER() OVER (PARTITION BY a.DivisionKey,
a.invdate,
a.HdrKey
ORDER BY a.QuestionKey) AS RowId
FROM mobile.StatusReport a WITH (NOLOCK)
INNER JOIN mobile.Question b WITH (NOLOCK) ON a.QuestionKey = b.PKey
AND b.QuestionType = 'rate'
AND InputType = 'numeric'
WHERE a.QuestionHdrKey = '200305685377000000'
GROUP BY a.QuestionHdrKey,
a.DivisionKey,
a.HdrKey,
a.InvDate,
a.QuestionKey)
SELECT a.DivisionKey,
a.InvDate AS ModifiedDate,
a.QuestionHdrKey,
a.HdrKey,
COUNT(DISTINCT a.QuestionKey) AS QuestionKey,
SUM(CAST(a.Value AS int)) AS value,
SUM(b.Rate) AS RATE
--case when a.invdate between '2020-05-09' and '2022-03-31' then case when then case when cast(Value as int)*5>5 then 5 else cast(Value as int)*5 end else cast(Value as int) end as value,c.QCount
FROM mobile.StatusReport a WITH (NOLOCK)
INNER JOIN mobile.Question b WITH (NOLOCK) ON a.QuestionKey = b.PKey
AND b.QuestionType = 'rate'
AND InputType = 'numeric'
INNER JOIN c WITH (NOLOCK) ON a.DivisionKey = c.DivisionKey1
INNER JOIN d WITH (NOLOCK) ON a.HdrKey = d.HdrKey
AND a.QuestionKey = d.QuestionKey
WHERE a.QuestionHdrKey = '200305685377000000'
--and a.HdrKey='210305757994230000'
AND d.RowId <= c.QCount
GROUP BY a.DivisionKey,
a.InvDate,
a.QuestionHdrKey,
a.HdrKey,
c.QCount;
I have this table queried in PowerBI which generates the below table:
The SQL is validated successfully in Information Design Tool but when trying to view its values, it shows an error in the code. How do I work around this?
Alright, after figuring out that "with as" doesn't work outside of the select function in the IDS, I've ditched the aliases and used sub-queries.
select HdrKey,a.DivisionKey,InvDate,RowId ,count(b.QuestionKey) as QCount,qCOUNT_,[value],POINT
from
(select distinct a.HdrKey,a.DivisionKey, a.InvDate, ROW_NUMBER() OVER(PARTITION BY QuestionHdrKey, DivisionKey, a.InvDate ORDER BY a.InvDate) AS RowId,
sum(cast([value] as int)) AS [value], COUNT(DISTINCT A.QuestionKey) AS qCOUNT_, SUM(B.Rate) AS POINT
from NominInventory.mobile.StatusReport a with(nolock)
inner join NominInventory.mobile.Question b with(nolock) on a.QuestionKey=b.PKey and B.QuestionType = 'rate' and InputType='numeric'
where a.QuestionHdrKey='200305685377000000'
GROUP BY a.HdrKey,a.DivisionKey, a.InvDate,QuestionHdrKey
) a
inner join NominInventory.Mobile.QuestionLocationMap b with(nolock) on a.DivisionKey=b.DivisionKey and b.QuestionHdrKey = '200305685377000000'
group by HdrKey,a.DivisionKey,InvDate,RowId,qCOUNT_,[value],POINT
having a.RowId<=count(b.QuestionKey)
It works well so far but I am stumped from here as I am brand new to this. This query finds the closest distance match, pairing up every item in the "FAILED" folder against everything that isn't in the "FAILED" folder.
There is a column "RouteID" in the "table p" that I want to match up with the min() aggregate.
I cannot process how to make the SELECT query simply show the associated "RouteID" column from tbl p but ultimately, I want to turn this into an update query that will SET a.Route = p.Route that is associated with the min()
Any help would be appreciated.
SELECT a.name, a.Reference1,
MIN(round(ACOS(COS(RADIANS(90-a.lat))
*COS(RADIANS(90-p.latpoint))
+SIN(RADIANS(90-a.lat))
*SIN(RADIANS(90-p.latpoint))
*COS(RADIANS(a.lon-p.longpoint)))
*3958.756,2)) AS 'DISTANCE'
FROM tblOrder AS a WITH (NOLOCK)
LEFT JOIN
(
SELECT b.lat AS latpoint, b.lon AS longpoint,
b.Sequence, b.routeid
from tblOrder b WITH (NOLOCK)
WHERE b.CUSTID = 180016
AND b.routeID <> 'FAILED'
AND b.StopType = 1
) AS p ON 1=1
WHERE a.CustID = 180016
AND a.RouteID = 'FAILED'
AND a.StopType = 1
AND P.RouteID <> 'FAILED'
GROUP BY
a.name, a.Reference1
You can select them separately and then join them
SELECT c.name, c.Reference1, q.RouteID
FROM
(
SELECT a.name, a.Reference1,
MIN(round(ACOS(COS(RADIANS(90-a.lat))
*COS(RADIANS(90-p.latpoint))
+SIN(RADIANS(90-a.lat))
*SIN(RADIANS(90-p.latpoint))
*COS(RADIANS(a.lon-p.longpoint)))
*3958.756,2)) AS 'DISTANCE'
FROM tblOrder AS a WITH (NOLOCK)
LEFT JOIN
(
SELECT b.lat AS latpoint, b.lon AS longpoint,
b.Sequence, b.routeid
from tblOrder b WITH (NOLOCK)
WHERE b.CUSTID = 180016
AND b.routeID <> 'FAILED'
AND b.StopType = 1
) AS p ON 1=1
WHERE a.CustID = 180016
AND a.RouteID = 'FAILED'
AND a.StopType = 1
AND P.RouteID <> 'FAILED'
GROUP BY
a.name, a.Reference1
) c
LEFT JOIN
(
SELECT b.lat AS latpoint, b.lon AS longpoint,
b.Sequence, b.routeid
from tblOrderRouteStops b WITH (NOLOCK)
WHERE b.CUSTID = 180016
AND b.routeID <> 'FAILED'
AND b.StopType = 1
) AS q
ON q.routeID = c.DISTANCE
I've got a query which returns 8 columns, 2 of them are sub queries which returns the maximum date. I would like to create 9th column which will return a number, asterisk or something to highlight the rows where date in column 1 is bigger than in column 2 but still keep all the rows. Is it possible somehow?
Edit:
this is the query
The columns I want to see the differences in are MaxExpDateGB and MaxExpDatePH
select
i.ITEM,
i.COMPANY,
count(distinct i.LOGISTICS_UNIT) as LocationsGB,
sum(on_hand_qty) as StockGB,
(select
Count(distinct location)
from
LOCATION_INVENTORY b where b.ITEM = i.ITEM and b.TEMPLATE_FIELD1 = '139' and b.TEMPLATE_FIELD4 is not null and b.TEMPLATE_FIELD5 is null) as LocationsPH,
(select
sum(on_hand_qty)
from
LOCATION_INVENTORY b where b.ITEM = i.ITEM and b.TEMPLATE_FIELD1 = '139' and b.TEMPLATE_FIELD4 is not null and b.TEMPLATE_FIELD5 is null) as StockPH,
MAX(i.Expiration_DATE) as MaxExpDateGB,
(select
MAX(a.Expiration_DATE)
from
LOCATION_INVENTORY a where a.ITEM = i.ITEM and a.TEMPLATE_FIELD1 = '139' and a.TEMPLATE_FIELD4 is not null and a.INVENTORY_STS = 'available' ) as MaxExpDatePH
from
LOCATION l inner join LOCATION_INVENTORY i on l.LOCATION = i.LOCATION inner join ITEM t on i.ITEM = t.ITEM
where
t.USER_DEF6 = '10'
and i.LOCATION = '000-gb-01'
group by
i.item,i.company
Without any refactoring
select *, case when LocationsPH > StockPH then '*' end flag
from (
select
i.ITEM,
i.COMPANY,
count(distinct i.LOGISTICS_UNIT) as LocationsGB,
sum(on_hand_qty) as StockGB,
(select
Count(distinct location)
from
LOCATION_INVENTORY b where b.ITEM = i.ITEM and b.TEMPLATE_FIELD1 = '139' and b.TEMPLATE_FIELD4 is not null and b.TEMPLATE_FIELD5 is null
) as LocationsPH,
(select
sum(on_hand_qty)
from
LOCATION_INVENTORY b where b.ITEM = i.ITEM and b.TEMPLATE_FIELD1 = '139' and b.TEMPLATE_FIELD4 is not null and b.TEMPLATE_FIELD5 is null
) as StockPH,
MAX(i.Expiration_DATE) as MaxExpDateGB,
(select
MAX(a.Expiration_DATE)
from
LOCATION_INVENTORY a where a.ITEM = i.ITEM and a.TEMPLATE_FIELD1 = '139' and a.TEMPLATE_FIELD4 is not null and a.INVENTORY_STS = 'available'
) as MaxExpDatePH
from
LOCATION l
inner join LOCATION_INVENTORY i on l.LOCATION = i.LOCATION inner join ITEM t on i.ITEM = t.ITEM
where
t.USER_DEF6 = '10'
and i.LOCATION = '000-gb-01'
group by
i.item,i.company
) t
I have a query that I need to add a column to. I can find many similar examples but nothing quite works right for this situation. There could be infinite CategoryIDs and I need to add the Sum(IsOutage) grouped by CategoryID. This is some sample data:
and here is the closest I have to getting it to work:
SELECT c.CategoryID
, c.Name
, COUNT(i.IssueID) AS TotalIssues
, AVG(DATEDIFF(MI, i.StartDate, i.ResolvedDate)) AS AvgDuration
,(Select COUNT(h.IssueID) From dbo.hdIssues AS h Where h.CategoryID = i.CategoryID AND IsOutage = 1 ) AS TotalOutages
FROM dbo.hdCategories AS c INNER JOIN
dbo.hdIssues AS i ON c.CategoryID = i.CategoryID
WHERE (i.StatusID = 3)
GROUP BY c.CategoryID, c.Name, TotalOutages
Am I close? Please advise and thanx in advance
EDIT: This is a mock up of what the result should look like:
If i correctly understand your needs this query should give you desired result:
SELECT x.* ,
y.SumIsOutage
FROM (SELECT c.CategoryID ,
c.Name ,
COUNT(i.IssueID) AS TotalIssues ,
AVG(DATEDIFF(MI, i.StartDate, i.ResolvedDate)) AS AvgDuration
FROM dbo.hdCategories AS c
INNER JOIN dbo.hdIssues AS i ON c.CategoryID = i.CategoryID
WHERE (i.StatusID = 3)
GROUP BY c.CategoryID, c.Name ) x
LEFT JOIN (SELECT DISTINCT i.CategoryId,
SUM(CONVERT(INT,i.isOutage)) OVER (PARTITION BY i.CategoryId) AS SumIsOutage
FROM dbo.hdIssues AS i ) y
ON x.CategoryId = y.CategoryId
You can use conditional aggregation. Also, you shouldn't group by totaloutages
SELECT
c.CategoryID
, c.Name
, COUNT(i.IssueID) AS TotalIssues
, AVG(DATEDIFF(MI, i.StartDate, i.ResolvedDate)) AS AvgDuration
,sum(case when IsOutage = 1 then 1 else 0 end) AS TotalOutages
FROM dbo.hdCategories AS c INNER JOIN
dbo.hdIssues AS i ON c.CategoryID = i.CategoryID
WHERE i.StatusID = 3
GROUP BY c.CategoryID, c.Name
You don't need another subquery for this count. Just count the rows that you're interested in:
COUNT(CASE WHEN i.IsOutage = 1 THEN 1 END)
In the context of your query:
SELECT
c.CategoryID
, c.Name
, COUNT(i.IssueID) AS TotalIssues
, AVG(DATEDIFF(MI, i.StartDate, i.ResolvedDate)) AS AvgDuration
, COUNT(CASE WHEN CONVERT(INT, i.IsOutage) = 1 THEN 1 END) AS TotalOutages
FROM
dbo.hdCategories AS c
INNER JOIN
dbo.hdIssues AS i
ON c.CategoryID = i.CategoryID
WHERE
i.StatusID = 3
GROUP BY
c.CategoryID
, c.Name
I have written a query like this. It is working and giving me the result which I wanted.
I have a SELECT query to get CAR_AMOUNT and HOTEL_AMOUNT.
But, I have to repeat the same SELECT query to get the SUM of both. I am not able to use alias name. How can I avoid this?
SELECT B.EMPLOYEE_ID,
(select SUM(AMOUNT)
FROM travel_reimbursements_items
WHERE type = 'CAR'
AND travel_request_no = B.travel_request_no
AND STATUS='APPROVED') as CAR_AMOUNT,
(select SUM(AMOUNT)
FROM travel_reimbursements_items
WHERE type = 'HOTEL'
AND travel_request_no = B.travel_request_no
AND STATUS='APPROVED') as HOTEL_AMOUNT,
NVL((select SUM(AMOUNT)
FROM travel_reimbursements_items
WHERE type = 'CAR'
AND travel_request_no = B.travel_request_no
AND STATUS='APPROVED'),0)
+NVL((select SUM(AMOUNT)
FROM travel_reimbursements_items
WHERE type = 'HOTEL'
AND travel_request_no = B.travel_request_no
AND STATUS='APPROVED'),0) as TOTAL
FROM TRAVEL_REQUEST_ITEM A
LEFT OUTER JOIN TRAVEL_REQUEST B
ON (B.TRAVEL_REQUEST_NO= A.TRAVEL_REQUEST_SR_NO)
select b.employee_id
, sum(case when c.type = 'CAR' then c.amount end) car_amount
, sum(case when c.type = 'HOTEL' then c.amount end) hotel_amount
, sum(c.amount) total
from travel_request_item a
left outer join travel_request b
on (b.travel_request_no= a.travel_request_sr_no)
left outer join travel_reimbursements_items c
on ( c.travel_request_no = b.travel_request_no
and c.type in ('CAR','HOTEL')
and c.status = 'APPROVED'
)
group by b.employee_id
Regards,
Rob.
This should work in oracle.
SELECT B.EMPLOYEE_ID,
SUM(CASE WHEN C.type = 'CAR' and C.STATUS='APPROVED' THEN C.AMOUNT ELSE 0 END) as CAR_AMOUNT,
SUM(CASE WHEN C.type = 'HOTEL' and C.STATUS='APPROVED' THEN C.AMOUNT ELSE 0 END) as HOTEL_AMOUNT,
SUM(CASE WHEN C.type IN ('CAR', 'HOTEL') and C.STATUS='APPROVED' THEN C.AMOUNT ELSE 0 END) as TOTAL
FROM TRAVEL_REQUEST_ITEM A
LEFT OUTER JOIN TRAVEL_REQUEST B ON (B.TRAVEL_REQUEST_NO= A.TRAVEL_REQUEST_SR_NO)
LEFT OUTER JOIN TRAVEL_REIMBURSEMENTS_ITEMS C ON (C.TRAVEL_REQUEST_NO = A.TRAVEL_REQUEST_SR_NO)
GROUP BY B.EMPLOYEE_ID
Just do a conditional sum based on the item type.