我有以下示例表:
DateAndTime MainsGasMeter Product_Order_MSB Product_Order_LSB
21/02/2017 03:53 53338200 7556 4331
21/02/2017 03:52 53338200 7556 4331
21/02/2017 03:51 53338200 7556 4331
21/02/2017 03:50 53338200 7556 4331
21/02/2017 03:49 53338100 7556 4324
21/02/2017 03:48 53338100 7556 4324
21/02/2017 03:47 53338100 7556 4324
21/02/2017 03:46 53338000 7556 4324
21/02/2017 03:45 53338000 7556 4324
21/02/2017 03:44 53338000 7556 4324
21/02/2017 03:43 53338000 7556 4324
21/02/2017 03:42 53337900 7556 4324
21/02/2017 03:41 53337900 7556 4324
21/02/2017 03:40 53337900 7556 4324
21/02/2017 03:39 53337900 7556 4323
21/02/2017 03:38 53337900 7556 4323
21/02/2017 03:37 53337900 7556 4323
21/02/2017 03:36 53337800 7556 4323
21/02/2017 03:35 53337800 7556 4323
21/02/2017 03:34 53337800 7556 4323
我可以编写一个SQL查询,在Product_Order_LSB
更改时它只返回数据行吗?
代码应该带回这个结果:
DateAndTime MainsGasMeter Product_Order_MSB Product_Order_LSB
21/02/2017 03:50 53338200 7556 4331
21/02/2017 03:40 53337900 7556 4324
数据来源为FurnaceHist.dbo.Furnace_db Furnace_db
。
我是SQL新手,所以非常感谢任何帮助!
我正在使用Microsoft SQL Server。
答案 0 :(得分:1)
此查询可能对您有用。假设您的版本低于2012年。
WITH CTE AS (
SELECT *,
ROW_NUMBER () OVER (PARTITION BY ProductOrderLSB ORDER BY ProductOrderLSB) AS RN
FROM tblTempTableDates)
SELECT C1.Dates,
C1.MainGasMeter,
C1.ProductOrderMSB,
C1.ProductOrderLSB FROM CTE C1
INNER JOIN (
SELECT ProductOrderLSB,
MAX(RN) AS RowNumber2
FROM CTE
GROUP BY ProductOrderLSB
) C2
ON C1.RN = C2.RowNumber2 AND C1.ProductOrderLSB = C2.ProductOrderLSB