假设 SQL SERVER 2005 或以上
CREATE TABLE #T (ID INT , ProductId INT, MemberId INT, SessionId VARCHAR(100), CreatedOn DATETIME, Quantity INT)
INSERT INTO #T SELECT 62,1 ,2 ,' ','2012-09-11',1
INSERT INTO #T SELECT 63, 2,2, ' ','2012-09-11',1
INSERT INTO #T SELECT 64, 1,0,'agzdeoqubwokfme05wwmne55','2012-09-11',1
INSERT INTO #T SELECT 65, 3,0,'agzdeoqubwokfme05wwmne55','2012-09-11',1
;With CTE AS
(SELECT
ID
,ProductId
,MemberId = MAX(MemberId) OVER(PARTITION BY ProductID ORDER bY(SELECT 1))
,SessionID
,CreatedOn = CONVERT(VARCHAR(10),MAX(CreatedOn) OVER(PARTITION BY ProductID ORDER bY(SELECT 1)),20)
,Quantity = SUM(Quantity) OVER(PARTITION BY ProductID ORDER bY(SELECT 1))
,Rn = ROW_NUMBER() OVER(PARTITION BY ProductID ORDER bY(SELECT 1))
FROM #T)
SELECT ID,ProductId,MemberId,SessionID,CreatedOn,Quantity FROM CTE WHERE Rn = 1
DROP TABLE #T
将给出结果为
ID ProductId MemberId SessionID CreatedOn Quantity
62 1 2 2012-09-11 2
63 2 2 2012-09-11 1
65 3 0 agzdeoqubwokfme05wwmne55 2012-09-11 1
最后,如果您想更新表格,请点击此处
UPDATE #T
SET
#T.ID = c.ID
,#T.ProductId =c.ProductId
,#T.MemberId = c.MemberId
,#T.SessionID = c.SessionID
,#T.CreatedOn = c.CreatedOn
,#T.Quantity = c.Quantity
FROM #T
INNER JOIN CTE c
ON #T.ID = c.ID
WHERE c.Rn = 1
结果是
ID ProductId MemberId SessionId CreatedOn Quantity
62 1 2 2012-09-11 2
63 2 2 2012-09-11 1
64 1 0 agzdeoqubwokfme05wwmne5 2012-09-11 1
65 3 0 agzdeoqubwokfme05wwmne55 2012-09-11 1
完整的查询是
;With CTE AS
(SELECT
ID
,ProductId
,MemberId = MAX(MemberId) OVER(PARTITION BY ProductID ORDER bY(SELECT 1))
,SessionID
,CreatedOn = CONVERT(VARCHAR(10),MAX(CreatedOn) OVER(PARTITION BY ProductID ORDER bY(SELECT 1)),20)
,Quantity = SUM(Quantity) OVER(PARTITION BY ProductID ORDER bY(SELECT 1))
,Rn = ROW_NUMBER() OVER(PARTITION BY ProductID ORDER bY(SELECT 1))
FROM #T)
UPDATE #T
SET
#T.ID = c.ID
,#T.ProductId =c.ProductId
,#T.MemberId = c.MemberId
,#T.SessionID = c.SessionID
,#T.CreatedOn = CONVERT(VARCHAR(10),c.CreatedOn,20)
,#T.Quantity = c.Quantity
FROM #T
INNER JOIN CTE c
ON #T.ID = c.ID
WHERE c.Rn = 1
SELECT * FROM #T
DROP TABLE #T
对于任何版本的 SQL
UPDATE #T
SET
#T.ID = c.ID
,#T.ProductId =c.ProductId
,#T.MemberId = c.MemberId
,#T.SessionID = c.SessionID
,#T.CreatedOn = c.CreatedOn
,#T.Quantity = c.Quantity
FROM #T
INNER JOIN (SELECT t.ID,t.ProductID,t.MemberId,t.SessionId,t.CreatedOn,x.Quantity
FROM #T t
JOIN (
SELECT
ID = MIN(ID)
,ProductID
,MemberId = MAX(MemberId)
,CreatedOn = MAX(CreatedOn)
,Quantity = SUM(Quantity)
FROM #T
GROUP BY ProductID
)X
ON t.ID =X.ID) c
ON #T.ID = c.ID
SELECT * FROM #T
DROP TABLE #T