我有以下查询我想添加两条记录,如16 + 16 = 32 + 15 = 47这样我想要30 + 15,= 47 + 15这样,
USE [ItemTable]
GO
/****** Object: Table [dbo].[NewPriceLabel] Script Date: 05/07/2016 03:46:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[NewPriceLabel](
[PLU] [varchar](25) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[Description] [varchar](40) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[Sizes] [varchar](7) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[OldPrice] [real] NULL,
[NewPrice] [real] NULL,
[Datechange] [datetime] NOT NULL CONSTRAINT [NewPriceLabel_Datechange] DEFAULT (getdate()),
CONSTRAINT [PK_NewPriceLabel] PRIMARY KEY CLUSTERED (
[PLU] ASC,
[Datechange] ASC
)WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = ON) ON [PRIMARY]) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
答案 0 :(得分:1)
我不是100%肯定你在问什么,但听起来你想要一笔累计金额。这个问题已经得到了回答:
https://stackoverflow.com/a/2120639/2565840
编辑:在您的情况下,我认为下面的查询应该有效
WITH
rows AS (
SELECT *, ROW_NUMBER() OVER (ORDER BY gps_time) AS rn
FROM rawtTackHistory_A2Z where car_id = 12956
),
differences AS (
SELECT mc.rn, mc.gps_time,DATEDIFF(second, mc.gps_time, mp.gps_time) time_diff
FROM rows mc
JOIN rows mp
ON mc.rn = mp.rn - 1
)
SELECT t1.gps_time, t1.time_diff, SUM(t2.time_diff) time_sum
FROM differences t1
INNER JOIN differences t2
ON t1.rn >= t2.rn
GROUP BY t1.rn, t1.gps_time, t1.time_diff
ORDER BY t1.rn
或者如果您正在使用SQL Server 2012或更高版本,则应该更快地运行:
SELECT gps_time
, DATEDIFF(second, LAG(gps_time) OVER (ORDER BY gps_time), gps_time) time_diff
, DATEDIFF(second, MIN(gps_time) OVER (ORDER BY gps_time), gps_time) time_sum
FROM rawtTackHistory_A2Z
ORDER BY gps_time
它使用了一个窗口子句(OVER
)。更多细节:https://msdn.microsoft.com/en-us/library/ms189461.aspx