To insert the results into an empty test table, check the approach that uses 'INTO':
drop table if exists #test
;WITH cte as
(
. . .
)
SELECT . . .
into #test
FROM cte
ORDER BY Firstpart, [date2], quantity
select * from #test
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Hi team
How do i insert the below union logic into one test table, how to insert ,as per the logic ,i am trying to insert this records into one test table ,not able to insert, can some one help for this logic
;WITH cte
as(SELECT Firstpart,'0001-01-01' [date2],NULL quantity
FROM (SELECT ,ROW_NUMBER() OVER(PARTITION BY Firstpart ORDER BY Firstpart) rr
FROM #Sourcetable)t WHERE rr=1
UNION ALL
SELECT FROM #Output
UNION ALL
SELECT Firstpart,'9999-12-31',NULL
FROM (SELECT *,ROW_NUMBER() OVER(PARTITION BY Firstpart ORDER BY Firstpart) rr
FROM #Sourcetable)t WHERE rr=1)
SELECT Firstpart,CASE WHEN [date2] = '0001-01-01' THEN 'STA'
WHEN [date2] = '9999-12-31' THEN 'FAU' ELSE [date2] END [date], quantity
FROM cte
ORDER BY Firstpart,[date2], quantity
Thank you! in advance!
To insert the results into an empty test table, check the approach that uses 'INTO':
drop table if exists #test
;WITH cte as
(
. . .
)
SELECT . . .
into #test
FROM cte
ORDER BY Firstpart, [date2], quantity
select * from #test
Hi @Naresh y ,
DROP TABLE IF EXISTS targettable
;WITH cte
as(SELECT Firstpart,'0001-01-01' [date2],NULL quantity
FROM (SELECT *,ROW_NUMBER() OVER(PARTITION BY Firstpart ORDER BY Firstpart) rr
FROM #Sourcetable)t WHERE rr=1
UNION ALL
SELECT * FROM #Output
UNION ALL
SELECT Firstpart,'9999-12-31',NULL
FROM (SELECT *,ROW_NUMBER() OVER(PARTITION BY Firstpart ORDER BY Firstpart) rr
FROM #Sourcetable)t WHERE rr=1)
SELECT Firstpart,CASE WHEN [date2] = '0001-01-01' THEN 'STA'
WHEN [date2] = '9999-12-31' THEN 'FAU' ELSE [date2] END [date], quantity,[date2]
INTO targettable
FROM cte
ORDER BY Firstpart,[date2], quantity
SELECT Firstpart,[date],quantity
FROM targettable
ORDER BY Firstpart,[date2], quantity
Output:
If this is the output you expect. So other people struggling with this problem may be because they don’t know the existence of a sorting column. I added a sorting column to the CTE I wrote earlier, and you can get the output you want based on this sorting column.
If you have any question, please feel free to let me know.
If the response is helpful, please click "Accept Answer" and upvote it.
Regards,
Echo
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.