我有一个表,它包含许多列,其中两个是group_id和access_id.Now 因记录不一致而引起的问题如下─ 记录的格式为
group_id access_id
100 1,
200 1,
300 1,
400 1,
100 2,
200 2,
300 2,
400 2,
100 3,
400 3,
100 4,
300 4,
所以你可以看到表中没有(group_id,access_id)-> (200,3),(300,3),(200,4),(400,4) ..
记录的条目
数据在生产服务器上有未知数量的组,每个access_id
有1到12 group_id
。
所以我需要形成一个查询为缺少的对(group_id,access_id)插入所有记录。
- (抱歉编辑能力差)
答案 0 :(得分:2)
INSERT INTO yourTable
SELECT group_id, t.x AS access_id
FROM yourTable CROSS JOIN
(
SELECT p.x FROM
(
VALUES (1), (2), (3), (4), (5), (6), (7), (8), (9), (10), (11), (12)
) P(x)
) AS t
EXCEPT
SELECT group_id, access_id FROM yourTable
尝试此代码在真实表名上替换YourTable。首先提交INSERT语句以查看结果SELECT语句
答案 1 :(得分:0)
CREATE PROCEDURE EXAMPLE
(
@accessid_range INT
)
AS
BEGIN
CREATE TABLE #LocalTempTable(group_id_temp INT, frequency INT)
INSERT INTO #LocalTempTable(group_id_temp, frequency)
(SELECT group_id,COUNT(group_id) AS frequency FROM SAMPLE2 GROUP BY group_id HAVING COUNT(group_id)<4);
--SELECT * FROM #LocalTempTable;
--SELECT group_id, access_id from SAMPLE2 WHERE group_id IN
--(SELECT group_id_temp FROM #LocalTempTable) GROUP BY group_id, access_id;
DECLARE @GROUPID INT
DECLARE GROUPIDs CURSOR LOCAL FOR SELECT group_id_temp FROM #LocalTempTable;
OPEN GROUPIDs
FETCH NEXT FROM GROUPIDs into @GROUPID
WHILE @@FETCH_STATUS = 0
BEGIN
--PRINT(@GROUPID)
--***********************************************************************************************************************
DECLARE @ACCESSID INT,
@COUNTER INT=1;
DECLARE ACSESSIDs CURSOR LOCAL FOR SELECT access_id FROM SAMPLE2 WHERE group_id=@GROUPID ORDER BY access_id;
OPEN ACSESSIDs
FETCH NEXT FROM ACSESSIDs into @ACCESSID
WHILE (@COUNTER <=@accessid_range)
BEGIN
--PRINT(@ACCESSID);
IF(@ACCESSID != @COUNTER)
INSERT INTO SAMPLE2 VALUES(@GROUPID,@COUNTER)
SET @COUNTER = @COUNTER + 1
FETCH NEXT FROM ACSESSIDs INTO @ACCESSID
END
CLOSE ACSESSIDs
DEALLOCATE ACSESSIDs
--*************************************************************************************************************************
FETCH NEXT FROM GROUPIDs into @GROUPID
END
CLOSE GROUPIDs
END