How to Delete duplicate Records:
here am showing the examples how to delete duplicate records in sqlserver.
First create the table with sample data
go
Suppose there is no unique key in table. using the below sample query you can delete the duplicate data.
2) How to get top n records from a give table
using ranking function.
using top
3) Suppose i have 3 tables with same data.First table have clustered index ,second table have non clustered
index and third table have no index. suppose i issue a command
select * from tablename
which will execute faster.
WITH CTE AS(select ID,name,AnnualSalary ,ManagerID,row_number() over( partition by ManagerID order by AnnualSalary desc) as rnkfrom Table1)select ID,name,AnnualSalary ,ManagerID from CTEwhere rnk = 2;WITH CTE AS(select ID,name,AnnualSalary ,ManagerID,dense_rank() over( partition by ManagerID order by AnnualSalary desc) as rnkfrom Table1)select ID,name,AnnualSalary ,ManagerID from CTEwhere rnk = 2;create table Table1 (ID int, Name varchar(50), AnnualSalary bigint, ManagerID int)insert into Table1 values (1,'Lisa',150000,null),(2,'Dan',110000,1),(3,'Oliver',180000,1),(4,'Dave',100000,1);insert into Table1 values (5,'Steve',200000,null),(6,'Alice',2050000,5),(7,'Damian',100000,5),(8,'Avery',210000,5),(9,'Mark',210000,5);select * from Table1
5) Returns pages from a cook book alternatevly
CREATE TABLE [dbo].[recipes](
[page_no] [int] NULL,
[title] [varchar](50) NULL
) ON [PRIMARY]
GO
DECLARE @table TABLE (
pageno int,
title varchar(30)
)
INSERT INTO @table
VALUES (1, 'pancake')
, (2, 'pizza')
, (3, 'pasta')
, (5, 'cookie')
;
WITH cte_pages
AS ( -- generate page numbers
SELECT
0 n,
MAX(pageno) maxpgno
FROM @table
UNION ALL
SELECT
n + 1 n,
maxpgno
FROM cte_pages
WHERE n <= maxpgno),
cte_left
AS ( --- even
SELECT
n,
ROW_NUMBER() OVER (ORDER BY n) rn
FROM cte_pages
WHERE n % 2 = 0),
cte_right
AS ( --- odd
SELECT
n,
ROW_NUMBER() OVER (ORDER BY n) rn
FROM cte_pages
WHERE n % 2 <> 0)
SELECT
tl.title left_title,
tr.title right_title
FROM cte_left l
INNER JOIN cte_right r
ON l.rn = r.rn
LEFT OUTER JOIN @table tl
ON tl.pageno = l.n
LEFT OUTER JOIN @table tr
ON tr.pageno = r.n
No comments:
Post a Comment