I have a query that is tracking production. Whenever a unit is produced I capture the timestamp, part number, delta time, and what the cycle time should have been, as well as others that aren't important to list here. In a SSRS report I count the rows and group them by hour and run efficiency calculations each hour based on the cycle times divided by the deltas. What I need is to add a column in my select statement that will flag whenever a part number changes so I can identify when a changeover has occurred by referencing it in my report.
Example: Select part number of row – part number of previous row as changeover
Every row would have a value that would always be 0 unless a changeover occurred then it would be a different value for that one row. I could have my report do its thing on any value <> 0.
As noted by SQLHound, if you're using SQL Server 2012 or another database that supports the LAG function then you can use this in your SQL query.
A SQL Server example:
SELECT
partnumber,
somevalue,
CASE
WHEN LAG(partnumber, 1) OVER (ORDER BY partnumber) <> partnumber THEN 1
ELSE 0
END AS PartNumberChangeOver
FROM ntest;
If you're source database doesn't support LAG, then can you tell us what database/version it is so we can try to provide an alternative solution.
Update: Additional example using a CTE, for SQL Server versions prior to 2012:
WITH ntestCTE
AS (SELECT
rownum = ROW_NUMBER() OVER (ORDER BY ntest.partnumber),
ntest.partnumber,
ntest.somevalue
FROM ntest)
SELECT
ntestCTE.partnumber,
ntestCTE.somevalue,
CASE
WHEN ntestCTE.partnumber <> prev.partnumber THEN 1
ELSE 0
END AS PartNumberChangeOver
FROM ntestCTE
LEFT JOIN ntestCTE prev
ON prev.rownum = ntestCTE.rownum - 1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.