SQL数据修复INSERT,可从具有相同ID的几行中检索数据

时间:2018-08-21 04:56:43

标签: sql sql-server

以下是“信用卡”表的摘录:

CreditCardID | ActivityId | CardDetails | TransactionDateTime    | TradingId
============================================================================
1              5         CardDetails1     2015-02-02 00:00:00.000    1
1              6         CardsDetails1    2016-02-02 00:00:00.000    1
1              5         CardDetails2     1999-02-02 00:00:00.000    2
1              6         CardsDetails2    2000-02-02 00:00:00.000    2
1              6         CardsDetails22   2000-02-03 00:00:00.000    2

我的解决方法是查找找到每个5,6组合,并插入带有ActivityId 66的新行,该行从ActivityId 5获取CardDetails,从ActivityId 6获取TransactionDateTime。

我的查询如下:

SELECT DISTINCT T.CreditCardID
INTO #temp
FROM CreditCard T WITH(NOLOCK)
WHERE ActivityId IN (5, 6)
GROUP BY T.CreditCardID
HAVING SUM(CASE WHEN T.ActivityId = 5 THEN 1 ELSE 0 END) > 0 AND
       SUM(CASE WHEN T.ActivityId = 6 THEN 1 ELSE 0 END) > 0 AND

SELECT B.* 
INTO #CreditCardTemp
FROM #temp A 
JOIN CreditCard B 
    ON A.CreditCardID = B.CreditCardID

INSERT INTO CreditCard (CreditCardID, ActivityId, CardDetails, TransactionDateTime, TradingId)
SELECT A.CreditCardID, 66, B.CardDetails, A.TransactionDateTime, B.TradingId
FROM #CreditCardTemp A
JOIN #CreditCardTemp B 
    ON A.CreditCardID = B.CreditCardID 
    AND A.TradingId = B.TradingId
WHERE A.ActivityId = 5
AND B.ActivityId = 6

但是,当我运行SELECT * FROM CreditCard时,我每6行获得66行,而每5和6组合我应该只获得1 66行(不管它有多少ActivityId 6)。

例如。如果在相同的CreditCardID和TradingId下有一个ActivityId 5和两个ActivityId 6,我应该只得到一个新的66行,而在这里,我得到了另外两个66行。

我认为我需要修改ActivityId 6联接以仅检索一条ActivityId 6记录,并且检索到的一条记录是Activity ID 6的最早记录。但是我需要编写此JOIN。

任何帮助将不胜感激。

谢谢!

1 个答案:

答案 0 :(得分:0)

我认为您的样本数据集可能不完整,但这就是我要这样做的方式。

我正在利用您数据中的模式,这些模式可能在您的真实数据中可能不存在

在您的示例中,每个对都方便地按TradingID值分组

SELECT 
CreditCardId,
66 As ActivitytId,
TradingID, 
MAX(CASE WHEN ActivityId = 5 THEN CardDetails ELSE NULL END) AS CardDetails,
MAX(CASE WHEN ActivityId = 6 THEN TransactionDateTime ELSE NULL END) AS TransactionDateTime
FROM CreditCard 
WHERE ActivityId IN (5,6)
GROUP BY TradingID, CreditCardId
HAVING MIN(ActivityId) = 5 AND MAX(ActivityId) = 6