我有两张桌子:
- @CAMERC
- @CAMERC_LOG
我必须使用列@CAMERC.MERC_LPR
中的值更新列@CAMERC_LOG.MERC_LPR
。
记录必须与MERC_KEY
匹配,但只有一条记录必须来自@CAMERC_LOG
- 最高MERC_KEY_LOG
,@CAMERC_LOG.MERC_LPR
不得为空或0。
我的问题是根据第二个表的结果更新一个表。我不知道如何正确地进行这样的更新?
表@CAMERC:
+----------+----------+
| MERC_KEY | MERC_LPR |
+----------+----------+
| 1 | 0.0000 |
| 2 | NULL |
| 3 | 0.0000 |
| 4 | 0.0000 |
+----------+----------+
表@CAMERC_LOG:
+----------+--------------+----------+
| MERC_KEY | MERC_KEY_LOG | MERC_LPR |
+----------+--------------+----------+
| 1 | 1 | 1.1000 |
| 1 | 2 | 2.3000 |
| 2 | 3 | 3.4000 |
| 2 | 4 | 4.4000 |
| 1 | 5 | 7.8000 |
| 1 | 6 | NULL |
| 2 | 7 | 0.0000 |
| 2 | 8 | 12.4000 |
| 3 | 1 | 12.1000 |
| 3 | 2 | 42.3000 |
| 3 | 3 | 43.4000 |
| 3 | 4 | 884.4000 |
| 4 | 5 | 57.8000 |
| 4 | 6 | NULL |
| 4 | 7 | 0.0000 |
| 4 | 8 | 412.4000 |
+----------+--------------+----------+
表创建代码:
DECLARE @CAMERC TABLE
(
MERC_KEY INT,
MERC_LPR DECIMAL(10,4)
)
DECLARE @CAMERC_LOG TABLE
(
MERC_KEY INT,
MERC_KEY_LOG INT,
MERC_LPR DECIMAL(10,4)
)
INSERT INTO @CAMERC(MERC_LPR, MERC_KEY) VALUES(0, 1),(NULL,2),(0,3),(0,4)
INSERT INTO @CAMERC_LOG(MERC_LPR, MERC_KEY, MERC_KEY_LOG) VALUES(1.1, 1,1),(2.3,1,2),(3.4,2,3),(4.4,2,4),(7.8, 1,5),(NULL,1,6),(0,2,7),(12.4,2,8),
(12.1, 3,1),(42.3,3,2),(43.4,3,3),(884.4,3,4),(57.8, 4,5),(NULL,4,6),(0,4,7),(412.4,4,8)
答案 0 :(得分:6)
试试这个:
SELECT
DISTINCT
s.UserID
FROM Members s
INNER JOIN Orders o
ON s.UserID = o.UserID
WHERE
s.UserID IN
(
SELECT UserID
FROM Orders
GROUP BY UserID
HAVING COUNT(*) > 5
)
我们的想法是从WITH DataSource AS
(
SELECT MERC_KEY
,ROW_NUMBER() OVER (PARTITION BY MERC_KEY ORDER BY MERC_KEY_LOG DESC) AS [RowID]
,MERC_LPR
FROM @CAMERC_LOG
WHERE MERC_LPR IS NOT NULL
AND MERC_LPR <> 0
)
UPDATE @CAMERC
SET MERC_LPR = B.[MERC_LPR]
FROM @CAMERC A
INNER JOIN DataSource B
ON A.[MERC_KEY] = B.[MERC_KEY]
AND B.[RowID] = 1
SELECT *
FROM @CAMERC
中删除无效记录,然后使用@CAMER_LOG
按ROW_NUMBER
排序。之后,我们仅在MERC_KEY_LOG
。
UPDATE