How to Generate row number as same as inserted without create or insert or cte - sql

I've this script:
Create table #temp (id int,name varchar(10),city varchar(10),sal int)
Insert into #temp
Select 2,'kishor','hyd', 100
Union all
Select 3,'kumar','sec', 200
Union all
Select 4,'santosh','kp', 300
Union all
Select 1,'sudeep','myp', 300
now I want to generate row number as same as data inserted without using a create or insert or CTE or Update commands, using a single select statement.
So that even after sorting by any order the row number column should not change its values

You should add auto-increment field to your table to save information about inserting order.
And then use for example ROW_NUMBER() to get a rownumber:
select #temp.*,
ROW_NUMBER() over (order by <your autoincrement field here> ) as RowNumber
from #temp

Related

Get unique rows from a cross reference table where all items reference each other

I have a cross reference table of part numbers (PN). There are 2 columns, PN and ALT_PN. All part numbers cross reference each other.
I need to create a report showing only the unique values in this table. Example, only show that A has alternate of B, and not show that B is an alternate of A.
I found solutions for Mysql that work, but they don't work in Oracle 11g.
Create table temp ( id integer primary key, PN varchar(10), Alt_PN
varchar(10));
insert into temp values(1,'A','B');
insert into temp values(2,'B','A');
insert into temp values(3,'X','Y');
insert into temp values(4,'Y','X');
insert into temp values(5,'C','D');
insert into temp values(6,'C','E');
insert into temp values(7,'D','C');
insert into temp values(8,'D','E');
insert into temp values(9,'E','C');
insert into temp values(10,'E','D');
i only want to return IDs of 1, 3, 5, 6 and 8
If all cross reference each other, just do:
select t.*
from temp t
where t.pn < t.alt_pn;
This will return one row from each pair, and works on any type.
If you are concerned that not all pairs are present, you can do:
select t.*
from (select t.*,
row_number() over (partition by least(t.pn, t.alt_pn), least(t.pn, t.alt_pn) order by t.pn) as seqnum
from t
) t
where seqnum = 1;

Hive- Delete duplicate rows using ROW_NUMBER()

How to delete duplicates using row_number() without listing all the columns from the table. I have a hive table with 50+ columns. If i want to delete duplicates based on a 2 columns below are the steps i followed
Create temp table as Create temptable as select * from (select
*,row_number() over(col1,col2) as rn from maintable) where rn=1)
Insert overwrite table maintable select * from temptable
But here in insert it fails because the new column rn is present in temptable; To avoid this column i would have to list all the rest of the columns.
And there is no Drop column option in hive. There also you need to use REPLACE function which again needs listing all the rest of the columns.
So any better idea for deleting duplicates in Hive based on 2 columns?
Spell out all column names from the original table for insert overwrite as the query computes a new column. No temp table is needed for this.
Insert overwrite table maintable
select col1,col2,col3 ---...col50
from (select t.*
,row_number() over(order by col1,col2) as rn
from maintable
) t
where rn = 1

Sql Server Issue During Update

Hello I am little bit confused to see the sql server behaviour on executing the query. According to mine the output should be "Priyanka" ,4
Declare #temp table(
Name Varchar(50),
amount int
)
insert #temp values ('Priyanka' ,10 )
Update #temp
set amount=amount-A.a
from (
select 'Priyanka' as Name,1 as a
union
select 'Priyanka' as Name,5 as a
)A
where [#temp].Name in (A.Name)
select * from #temp
But
the output
Name amount
Priyanka 9
Can any one Please tell me why this is happened.
Standard SQL doesn't support a from clause with update and you'd instead have to write your access to other tables as a direct subquery in the set clause. If you did that, you'd get the error "subquery returned more than one value" and have some idea of the issue.
Unfortunately, the Microsoft extension to SQL that allows a FROM clause also silently ignores the fact that multiple rows may match, uses one of those rows and ignores the others.1
If you're going to use this extension, it's up to you to carefully ensure that you don't have multiple matches to a single row in the target table.
I'd rearrange your query, something like:
Declare #temp table(
Name Varchar(50),
amount int
)
insert #temp values ('Priyanka' ,10 )
;With A as
(
select 'Priyanka' as Name,1 as a
union
select 'Priyanka' as Name,5 as a
)
Update t
set amount=amount-Aa.a
from
#temp t
cross apply
(select SUM(a) as a from A where Name = t.Name) Aa
select * from #temp
Where I use the cross apply to aggregate the data down to a single row per target row.
1Importantly, though, it does support the concept that the effects of an UPDATE are applied "as if" all rows (and columns within them) are updated in parallel. So you don't get that first the update applies using one row and then the second update gets to update an already updated row.
You need to SUM the values of the union entries. Simply UNION the entries it have multiple entries so it may take any one entry and ignore the remains.
For your case the following query will work:
DECLARE #temp TABLE (NAME VARCHAR(50), amount INT)
INSERT #temp
VALUES ('Priyanka', 10)
UPDATE t
SET amount = t.amount - A.a
FROM #temp t
JOIN (
SELECT NAME, SUM(a) AS a FROM (
SELECT 'Priyanka' AS NAME, 1 AS a
UNION
SELECT 'Priyanka' AS NAME, 5 AS a
) c
GROUP BY NAME
) A ON A.NAME = t.NAME
SELECT * FROM #temp

How to Update Executed table result into the same table?

I have created a table tbl_Dist with Column names District and DistCode, there were many duplicate values in the District table so i have removed all the duplicates value using this statement:
select distinct District from tbl_Dist;
its done, but i am not getting how to update the results of the above executed query to the table tbl_Dist?
You can as the below:
-- Move temp table
SELECT DISTINCT District INTO TmpTable FROM tbl_Dist
-- Delete all data
DELETE FROM tbl_Dist
-- Insert data from temp table
INSERT INTO tbl_Dist
SELECT * FROM TmpTable
Updated
Firstly, run this query. You will have a temp table with distinct data of main table (tbl_Dist)
-- Move temp table
SELECT DISTINCT District INTO TmpTable FROM tbl_Dist
Then run the below query to delete all data
DELETE FROM tbl_Dist
Finally, run the below query to insert all distinct data to main table.
-- Insert data from temp table
INSERT INTO tbl_Dist
SELECT * FROM TmpTable
You need Delete not Update
;with cte as
(
Select row_number() over(partition by District order by (select null)) as rn,*
From yourtable
)
Delete from cte where Rn > 1
To check the records that will be deleted use this.
;with cte as
(
Select row_number() over(partition by District order by (select null)) as rn,*
From yourtable
)
Select * from cte where Rn > 1
If you want to keep this query you can keep it in a view the write an update query through that view.The table will be updated
try this script
DELETE FROM tbl_Dist
WHERE District = District
AND DistCode > DistCode

SQL Server query for getting single value from each column into a single column

I'll start directly by explaining with an example. Suppose I have a table which has 3 columns as shown.
Now what I am trying to achieve is, I want the first values of each individual column into a single column. So it would be something like this,
I have tried a few queries here including using TOP 1 and other incorrect ways. But I am still missing something here to achieve the exact output.
Need some guidance here on how to achieve this. Thank you.
SAMPLE TABLE
SELECT * INTO #TEMP
FROM
(
SELECT 1 BATCH_ID,'AAA' ASSIGNMENTTITLE,'FILE' ASSIGNMENTTYPE
UNION ALL
SELECT 1,'AAA1','FILE'
UNION ALL
SELECT 1,'AAA','FILE'
)TAB
If you need the second row specifically you can do the below
QUERY
;WITH CTE AS
(
-- Order row according to default format
SELECT ROW_NUMBER() OVER(ORDER BY (SELECT(0))) RNO,*
FROM #TEMP
)
SELECT CAST(BATCH_ID AS VARCHAR(20)) FROM CTE WHERE RNO=2
UNION ALL
SELECT ASSIGNMENTTITLE FROM CTE WHERE RNO=2
UNION ALL
SELECT ASSIGNMENTTYPE FROM CTE WHERE RNO=2
Click here to view result
UPDATE
Since there are 3 items in each record, it can be puzzled unless and otherwise an a column is for each items in a record.
;WITH CTE AS
(
-- Order row according to default format
SELECT ROW_NUMBER() OVER(ORDER BY (SELECT(0))) RNO,*
FROM #TEMP
)
SELECT CAST(BATCH_ID AS VARCHAR(20)),RNO
FROM CTE
UNION ALL
SELECT ASSIGNMENTTITLE,RNO
FROM CTE
UNION ALL
SELECT ASSIGNMENTTYPE,RNO
FROM CTE
ORDER BY RNO
Click here to view result
You can use the concat() function to create a column consisting of all the desired values
More info here
Simply you can try this. If want specific for a row use rowid. For all columns Use unpivot
create table #temp(id int, name varchar(100), title varchar(100))
insert into #temp values(1,'aaa','file')
insert into #temp values(1,'aaas','filef')
insert into #temp values(1,'aaaww','filefs')
select * from #temp
select top 1 cast(id as varchar) title from #temp
union
select top 1 name from #temp
union
select top 1 title from #temp
drop table #temp
This might help you
select top 1 convert(varchar(10), batch_id) ASSIGNMENTTITLE from table
union all
select top 1 ASSIGNMENTTITLE from table
union all
select top 1 ASSIGNMENTTYPE from table
If this is really what you want: "I want the first values of each individual column into a single column" it would be:
select ASSIGNMENTTITLE
from (
select min(convert(varchar(10), batch_id)) ASSIGNMENTTITLE,
1 ColOrder from table
union all
select min(ASSIGNMENTTITLE),
2 ColOrder from table
union all
select min(ASSIGNMENTTYPE),
3 ColOrder from table
) as data
order by ColOrder