insert into `table2`(id,name,address,tel,email) values (1,'bb',NULL,NULL,NULL),(2,NULL,'spk',NULL,NULL),(3,NULL,NULL,'02--','[email protected]');
SELECT @rownum:=@rownum+1 'id', NAME, address, tel, email FROM (
SELECT id, NAME, address, tel, email FROM table1
UNION ALL
SELECT id, NAME, address, tel, email FROM table2) a
,(SELECT @rownum:=0) r
-- REGION : สำหรับ test เท่านั้นค่ะ
CREATE TABLE #OHH_WHATS_THAT
(
[ID] INT NULL,
[NAME] NVARCHAR(MAX) NULL ,
[ADDRESS] NVARCHAR(MAX) NULL ,
[TEL] NVARCHAR(100) NULL ,
[EMAIL] NVARCHAR(100) NULL
);
DECLARE @COUNTER AS INT ;
DECLARE @INNERCOUNTER AS INT ;
DECLARE @pID AS INT ;
DECLARE @pNAME AS NVARCHAR(MAX) ;
DECLARE @pADDR AS NVARCHAR(MAX) ;
DECLARE @pTEL AS NVARCHAR(MAX) ;
DECLARE @pEMAIL AS NVARCHAR(MAX) ;
SET @COUNTER = 0 ;
WHILE(@COUNTER < 10)
BEGIN
SET @INNERCOUNTER = 0 ;
SET @pNAME = REPLICATE(CHAR(ASCII('A')+@COUNTER) ,3);
SET @pADDR = @pNAME ;
SET @pTEL = '02-' + @pNAME ;
SET @pEMAIL = @pNAME + '@' + @pNAME + '.' + @pNAME ;
WHILE (@INNERCOUNTER < 3)
BEGIN
SET @pID = (@INNERCOUNTER+1) + (@COUNTER*3) ;
IF (@INNERCOUNTER = 0)
INSERT INTO #OHH_WHATS_THAT VALUES
(@pID ,@pNAME ,NULL ,NULL ,NULL ) ;
ELSE IF (@INNERCOUNTER = 1)
INSERT INTO #OHH_WHATS_THAT VALUES
(@pID ,NULL ,@pADDR ,NULL ,NULL ) ;
ELSE
INSERT INTO #OHH_WHATS_THAT VALUES
(@pID ,NULL ,NULL ,@pTEL ,@pEMAIL ) ;
SET @INNERCOUNTER = @INNERCOUNTER +1 ;
END ;
SET @COUNTER = @COUNTER+1 ;
END ;
-- ENDREGION : สำหรับ test เท่านั้นค่ะ
SELECT * FROM #OHH_WHATS_THAT ;
WITH REORDER_TABLE AS
(
SELECT ROW_NUMBER() OVER(ORDER BY [ID]) AS ROW_NO ,* FROM #OHH_WHATS_THAT
)
SELECT QR01.MERGE_ID ,QR01.[NAME] ,QR02.[ADDRESS] ,QR03.[TEL] ,QR03.[EMAIL]
FROM
(
SELECT (ROW_NO / 3)+1 AS MERGE_ID ,*
FROM REORDER_TABLE WHERE ((ROW_NO %3)=1)
) AS QR01 ,
(
SELECT (ROW_NO / 3)+1 AS MERGE_ID ,*
FROM REORDER_TABLE WHERE ((ROW_NO %3)=2)
) AS QR02 ,
(
SELECT (ROW_NO / 3) AS MERGE_ID ,*
FROM REORDER_TABLE WHERE ((ROW_NO %3)=0)
) AS QR03
WHERE (QR01.MERGE_ID = QR02.MERGE_ID) AND (QR02.MERGE_ID = QR03.MERGE_ID)
-- REGION : สำหรับ test เท่านั้นค่ะ
DROP TABLE #OHH_WHATS_THAT ;
-- ENDREGION : สำหรับ test เท่านั้นค่ะ