I have this data
Id Campo ----------- ---------- 1 id_recibo 2 col_2 3 col_65 4 UNDCAP 5 id_recibo 6 col_2 7 col_65 8 UNDCAP
And I need to do something like SELECT DISTINCT
obtaining the data in order of appearance and not in the ascending order by default that is obtained.
If I do a SELECT DISTINCT
I get this:
campo -------- col_2 col_65 id_recibo UNDCAP
Here the code:
IF OBJECT_ID('tempdb..#tmp') IS NOT NULL DROP TABLE #tmp CREATE TABLE #tmp ( Id INT IDENTITY, Campo VARCHAR(MAX) ) INSERT INTO #tmp (Campo) VALUES ('id_recibo'), ('col_2'), ('col_65'), ('UNDCAP'), ('id_recibo'), ('col_2'), ('col_65'), ('UNDCAP') SELECT * FROM #tmp SELECT DISTINCT campo FROM #tmp
The result I need is like this:
campo ---------- id_recibo col_2 col_65 UNDCAP
I tried some like this, but It doesn’t work, because the order is variable:
SELECT A.Campo AS NuevoOrden FROM (SELECT DISTINCT CAMPO FROM #tmp) A ORDER BY NEWID()
Advertisement
Answer
I think you just want:
select campo from t group by campo order by min(id);