Looking up the first row of results - sql-server

I have a history table containing a snapshot of each time a record is changed. I'm trying to return a certain history row with the original captured date. I am currently using this at the moment:
select
s.Description,
h.CaptureDate OriginalCaptureDate
from
HistoryStock s
left join
( select
StockId,
CaptureDate
from
HistoryStock
where
HistoryStockId in ( select MIN(HistoryStockId) from HistoryStock group by StockId )
) h on s.StockId = h.StockId
where
s.HistoryStockId = #HistoryStockId
This works but with 1 Million records its on the slow side and I'm not sure how to optimize this query.
How can this query be optimized?
UPDATE:
WITH OriginalStock (StockId, HistoryStockId)
AS (
SELECT StockId, min(HistoryStockId)
from HistoryStock group by StockId
),
OriginalCaptureDate (StockId, OriginalCaptureDate)
As (
SELECT h.StockId, h.CaptureDate
from HistoryStock h join OriginalStock o on h.HistoryStockId = o.HistoryStockId
)
select
s.Description,
h.OriginalCaptureDate
from
HistoryStock s left join OriginalCaptureDate h on s.StockId = h.StockId
where
s.HistoryStockId = #HistoryStockId
I've update the code to use CTE but I'm not better off performance wise, only have small performance increase. Any ideas?
Just another note, I need to get to the first record in the history table for StockId and not the earliest Capture date.

I am not certain I understand entirely how the data works from your query but nesting queries like that is never good for performance in my opinion. You could try something along the lines of:
WITH MinCaptureDate (StockID, MinCaptureDate)
AS (
SELECT HS.StockID
,MIN(HS.CaptureDate) AS OriginalCaptureDate
FROM HistoryStock HS
GROUP BY
HS.Description
)
SELECT HS.Description
,MCD.OriginalCaptureDate
FROM HistoryStock HS
JOIN MinCaptureDate MCD
ON HS.StockID = MCD.StockID
WHERE HS.StockID = #StockID

I think i see what you are trying to achieve. You basically want the description of the specified history stock record, but you want the date associated with the first history record for the stock... so if your history table looks like this
StockId HistoryStockId CaptureDate Description
1 1 Apr 1 Desc 1
1 2 Apr 2 Desc 2
1 3 Apr 3 Desc 3
and you specify #HistoryStockId = 2, you want the following result
Description OriginalCaptureDate
Desc 2 Apr 1
I think the following query would give you a slightly better performance.
WITH OriginalStock (StockId, CaptureDate, RowNumber)
AS (
SELECT
StockId,
CaptureDate,
RowNumber = ROW_NUMBER() OVER (PARTITION BY StockId ORDER BY HistoryStockId ASC)
from HistoryStock
)
select
s.Description,
h.CaptureDate
from
HistoryStock s left join OriginalStock h on s.StockId = h.StockId and h.RowNumber = 1
where
s.HistoryStockId = #HistoryStockId

Related

Display of online users on the system

I don't know exactly where I'm wrong, but I need a list of all the workers who are currently at work (for the current day), this is my sql query:
SELECT
zp.ID,
zp.USER_ID,
zp.Arrive,
zp.Deppart,
zp.DATUM
FROM time_recording as zp
INNER JOIN personal AS a on zp.USER_ID, = zp.USER_ID,
WHERE zp.Arrive IS NOT NULL
AND zp.Deppart IS NULL
AND zp.DATUM = convert(date, getdate())
ORDER BY zp.ID DESC
this is what the data looks like with my query:
For me the question is, how can I correct my query so that I only get the last Arrive time for the current day for each user?
In this case to get only these values:
Try this below script using ROW_NUMBER as below-
SELECT * FROM
(
SELECT zp.ID, zp.USER_ID, zp.Arrive, zp.Deppart, zp.DATUM,
ROW_NMBER() OVER(PARTITION BY zp.User_id ORDER BY zp.Arrive DESC) RN
FROM time_recording as zp
INNER JOIN personal AS a
on zp.USER_ID = zp.USER_ID
-- You need to adjust above join relation as both goes to same table
-- In addition, as you are selecting nothing from table personal, you can drop the total JOIN part
WHERE zp.Arrive IS NOT NULL
AND zp.Deppart IS NULL
AND zp.DATUM = convert(date, getdate())
)A
WHERE RN =1
you can try this:
SELECT DISTINCT
USER_ID,
LAR.LastArrive
FROM time_recording as tr
CROSS APPLY (
SELECT
MAX(Arrive) as LastArrive
FROM time_recording as ta
WHERE
tr.USER_ID = ta.USER_ID AND
ta.Arrive IS NOT NULL
) as LAR

SQL : Im tring to work out, how to return last action per member

Id Mshp_Id Action
1 9029 Register
2 9029 Create CV
3 8476 Register
4 8476 Create CV
5 8476 JOB SEARCH
I want to return the two membership ID's and their latest action.
so what would be left is ID 2 AND 5 ONLY.
If you are using SQL Server 2012+, you can use LAST_VALUE
SELECT ID,
,mshp_id
,action
FROM (
SELECT *,LAST_VALUE(id) OVER (PARTITION BY mshp_id
ORDER BY ID
ROWS BETWEEN UNBOUNDED PRECEDING
AND UNBOUNDED FOLLOWING
) last_val
FROM YOUR_TABLE
) a
WHERE id = last_val
ORDER BY ID
Check Demo here
Output
Last action per member can be fetched through the following ways
Solution 1:
select Id, Mshp_Id, Action from (
select *, row_number() over (partition by Mshp_Id order by id desc) r from user_action
) a
where a.r = 1
order by id
Solution 2
select u.* from user_action u
join (select Mshp_Id, max(id) id from user_action
group by Mshp_Id ) a
on a.Mshp_Id = u.Mshp_Id and a.id = u.id
order by u.id
Good luck with your work !

SAP B1 query using pivot for yearly comparison

Requirement: I want to compare the years(2018) sales and gross profit over last year(2017).
Solution: I have tried using the query below and I get the expected results.
Month | prevSales | prevGP | currentSales | currGP
Jan | 1234567.00| 1234567.00| 1234567.00 | 1234567.00
Feb | 1234567.00| 1234567.00| 1234567.00 | 1234567.00
Problem: The query took so long to produce results, it's almost one minute to display results.
SELECT P.[monName],
ISNULL([2017],0) as [prev],
ISNULL(P.[prevGP],0) [prevGP],
ISNULL([2018],0) as [curr],
ISNULL(P.[currGP],0) [currGP]
FROM (
SELECT LEFT(DATENAME(MONTH,T1.DocDate),3) [monName],
MONTH(T1.DocDate) [monNum],
ROUND((T1.Doctotal-T1.VatSum-T1.TotalExpns),0) AS [BAL],
(SELECT Sum(A.GrosProfit)
FROM OINV A
WHERE A.CANCELED='N' AND A.DocStatus='C' AND RIGHT(A.NumAtCard,9)<>'CANCELLED'
AND YEAR(A.DocDate)=YEAR(GETDATE())-1 AND MONTH(A.DocDate)=MONTH(T1.DocDate) ) [prevGP],
(SELECT SUM(B.GrosProfit)
FROM OINV B
WHERE B.CANCELED='N' AND B.DocStatus='C' AND RIGHT(B.NumAtCard,9)<>'CANCELLED'
AND YEAR(B.DocDate)=YEAR(GETDATE()) AND MONTH(B.DocDate)=MONTH(T1.DocDate) ) [currGP],
year(T1.Docdate) as [year]
FROM dbo.OCRD T0
LEFT JOIN dbo.OINV T1 ON T1.CardCode = T0.CardCode
Where RIGHT(T1.Numatcard,9)<>'CANCELLED' AND T1.CANCELED='N'
AND T0.[CardType] ='C' AND T1.DocStatus='C'
) S
PIVOT ( SUM(S.[BAL]) FOR [year] IN ([2017],[2018])) P
What could I possibly do to make the query efficient. I believe there is something to do with the pivot.
Thank you.
The problem with your view are the subqueries. If you want to improve the performance of your query you need to avoid the use of those subqueries.
For example, you can create an sql view that returns the information you need. Then you join your current query with that view and you remove the subqueries.
You could do it like this.
create view InvoiceInfoByMonth
as
select sum(GrosProfit) as GrosProfit, year(docdate) as DocYear, month(docdate) as DocMonth
from OINV
WHERE CANCELED='N' AND DocStatus='C' AND RIGHT(NumAtCard,9)<>'CANCELLED'
group by year(DocDate), month(DocDate)
GO
SELECT P.[monName],
ISNULL([2017],0) as [prev],
ISNULL(P.[prevGP],0) [prevGP],
ISNULL([2018],0) as [curr],
ISNULL(P.[currGP],0) [currGP]
FROM (
SELECT LEFT(DATENAME(MONTH,T1.DocDate),3) [monName],
MONTH(T1.DocDate) [monNum],
ROUND((T1.Doctotal-T1.VatSum-T1.TotalExpns),0) AS [BAL],
T2.GrosProfit as prevGP, T3.GrosProfit as currGP,
year(T1.Docdate) as [year]
FROM dbo.OCRD T0
LEFT JOIN dbo.OINV T1 ON T1.CardCode = T0.CardCode
left join InvoiceInfoByMonth T2 ON T2.DocYear = year(getdate())-1 and month(T1.DocDate) = T2.DocMonth
left join InvoiceInfoByMonth T3 ON T3.DocYear = year(getdate()) and month(T1.DocDate) = T3.DocMonth
Where RIGHT(T1.Numatcard,9)<>'CANCELLED' AND T1.CANCELED='N'
AND T0.[CardType] ='C' AND T1.DocStatus='C'
) S
PIVOT ( SUM(S.[BAL]) FOR [year] IN ([2017],[2018])) P
In my system, the query execution time improved from 1 minute to 1 second.

SQL Pull the latest datediff for each Category

I have two tables.
Repair -
RepairID, EquipID, RepairDate
Events -
EventID, EquipID, ReturnDate, CustomerID
I am trying to determine who the last customer was that returned the equipment, before the repair was done. Equipment could have been returned multiple times in the past, but I only need to track the very last customer that returned it.
Final result will include CustomerID, EquipID, ReturnDate, RepairDate
My SQLFiddle for a sample DDL and query:
http://sqlfiddle.com/#!3/f2691/6/0
This returns all the customers, not only the very last one that returned.
Does that return what you expect?
Option 1:
SELECT E.EquipID,
E.CustomerID,
max(E.ReturnDate) MAXRETURN
FROM Repair R
CROSS APPLY (
SELECT *,
row_number() OVER (
PARTITION BY EquipID ORDER BY ReturnDate DESC
) AS RN
FROM Event E
WHERE R.RepairDate > E.ReturnDate
AND E.EquipID = R.EquipID
) E
WHERE E.RN = 1
GROUP BY E.EquipID,
E.CustomerID
Option 2:
SELECT E.EquipID,
E.CustomerID,
max(E.ReturnDate) MAXRETURN
FROM (
SELECT E.*,
row_number() OVER (
PARTITION BY E.EquipID ORDER BY E.ReturnDate DESC
) AS RN
FROM Event E
INNER JOIN Repair R
ON E.EquipID = R.EquipID
WHERE R.RepairDate > E.ReturnDate
) E
WHERE E.RN = 1
GROUP BY E.EquipID,
E.CustomerID

Sql Server double subquery

I have a table which is kinda like an historic table... so I have data like this
idA numberMov FinalDate
1 10 20090209
2 14 20090304
1 12 20090304
3 54 20080508
4 42 20090510
... ... ....
I need to retrieve the numberMov based on the newest finalDate from each idA so I use this
select a.numberMov from (select idA, max(finalDate) maxDate from table1 group by idA) as b inner join table1 a on a.idA=b.idA and a.finalDate = b.maxDate
Now I have another query like this
select m fields from n tables where n5.numberMov in ("insert first query here")
I feel like there is a better solution but can't think of any, I really dont like having two subqueries in there.
Any suggestions?
Not enough information to test it myself but something like this might work.
select m fields
from a inner join
(select numberMov,
max(FinalDate) as maxDate
from a
group by numberMov) b
on a.numberMov = b.numberMov
and a.FinalDate = b.maxDate inner join
n tables on a.numberMov = n.numberMov
You don't say which edition of SQL server, but this will work in SQL 2005+
;WITH rankCTE
AS
(
SELECT idA
,numberMov
,FinalDate
,ROW_NUMBER() OVER (PARTITION BY idA
ORDER BY FinalDate DESC
) AS rn
FROM table1
)
,latestCTE
AS
(
SELECT idA
,numberMov
,FinalDate
FROM rankCTE
WHERE rn = 1
)
SELECT m fields
FROM n tables
WHERE n5.numberMov IN (SELECT numberMov FROM latestCTE)

Resources