Select a random row from each group SQL Server - sql-server

I have a table like below
ID Code Age
----------------
1 4758 21
1 7842 14
1 9821 23
1 6842 9
2 8472 24
2 7558 31
2 7841 28
3 7881 38
3 8794 42
3 4871 43
For each ID, I want to select one of the rows at random like so
ID Code Age
----------------
1 7842 14
2 7841 28
3 4871 43
Is this possible in SQL Server?

select top 1 with ties id,code,age
from
table
order by row_number() over (partition by id order by rand())
Update: as per this Return rows in random order, you have to use NEWId,since RAND() is fixed for the duration of the SELECT on MS SQL Server.
select top 1 with ties id,code,age
from
table
order by row_number() over (partition by id order by NEWID())

Use Newid() in order by clause of Row_number()
SELECT [ID], [Code], [Age]
FROM (SELECT *,
Row_number()
OVER(
PARTITION BY ID
ORDER BY Newid()) RNO
FROM #Table1)A
WHERE RNO = 1

with cte as
(
select *,rank() over ( partition by id order by Newid()) as rn from #c
)
select id,code,age from cte where rn=1

To select different sets each time, use checksum(newid()) in the order by clause.
Query
;with cte as(
select *, rn = row_number() over(
partition by ID
order by abs(checksum(newid())) % 15
)
from [your_table_name]
)
select * from cte
where rn = 1;

Related

SQL Server Query for account statement

How can I generate last three transactions from the below table?
Date Tran dr cr total
-------------------------------------
2017-04-13
2017-07-15
2017-07-15
2017-10-17
2017-10-17 abc 10 10
2017-11-12 def 10 20
2017-11-12 ghi 5 15
I'm using SQL Server 2012
Like this you should your expected result:
SELECT * FROM
(
SELECT TOP 3 *
FROM TransactionTable
ORDER BY [Date] DESC
) AS t
ORDER by t.[Date]
if your requirement is to get the 3 transactions with the latest date. you can use either of the following.
Simple Order by :
select
top 3
* from YourTable
where isnull(Tran,'')<>''
order by [Date] desc
using Row Number
;with cte
as
(
select
seqno = row_number() over(order by [date] desc),
*
from YourTable
where isnull(Tran,'')<>''
)
select
* from cte
where SeqNo <=3
order by SeqNo desc

sequence Rank in query

I would like to get sequence number in mssql. Please see below.
There is a table.
UserID Score TeamID
------------------------------
1 100 1
2 200 1
3 500 2
4 600 2
5 700 2
6 1000 3
I would like to sort by total score group by team. see below
RankID UserID Score TeamID TotalScore
-----------------------------------------------------------
1 3 500 2 1800
1 4 600 2 1800
1 5 700 2 1800
2 6 1000 3 1000
3 1 100 1 300
3 2 200 1 300
I want to code only one sql query. Help me someone how can I do this? Thanks.
This should work:
;WITH TotalScore AS (
SELECT UserID, Score, TeamID,
SUM(Score) OVER (PARTITION BY TeamID) AS TotalScore
FROM mytable
)
SELECT DENSE_RANK() OVER (ORDER BY TotalScore DESC) AS RankID,
UserID, Score, TeamID, TotalScore
FROM TotalScore
ORDER BY TotalScore DESC, Score
The Common Table Expression used calculates the total score per TeamID using windowed version of SUM. Using DENSE_RANK together with this calculated field we can easily generate the required RankID.
You can try this
SELECT
RANK() OVER(ORDER BY i.TotalScore DESC) AS RankID
,A.*
FROM
(
SELECT
UserID
,Score
,TeamID
,(SELECT SUM(Score) FROM yourTable tb2 WHERE tb2.TeamID = tb1.TeamID) AS TotalScore
FROM yourTable tb1
) A
ORDER BY A.TotalScore DESC
Have a Try with below,
Select DENSE_RANK() over(Order by (Select Sum(Score) from #tablename V where V.TeamID=T.TeamID ) desc )RankID
,*,
Sum(Score) over(Partition by TeamID) TotalScore from #tablename T
order by DENSE_RANK() over(Order by (Select Sum(Score) from #tablename V where V.TeamID=T.TeamID ) desc )
Dense Rank in the 'Order by' to sort the results by RANK Id and the same is used in Select statement, Subquery in the Dense Rank will rank based on the sum(Score) for a TeamID

SQL Server query should return max value records

I have table like this:
id_Seq_No emp_name Current_Property_value
-----------------------------------------------
1 John 100
2 Peter 200
3 Pollard 50
4 John 500
I want the max record value of particular employee.
For example, John has 2 records seq_no 1, 4. I want 4th seq_no Current_Property_Value in single query.
Select
max(id_Seq_No)
from
t1
where
emp_name = 'John'
To get the Current_Property_value, just order the results by id_Seq_No and get the first one:
SELECT
TOP 1 Current_Property_value
FROM
table
WHERE
emp_name = 'John'
ORDER BY
id_Seq_No DESC
this will give highest for all tied employees
select top 1 with ties
id_Seq_No,emp_name,Current_Property_value
from
table
order by
row_number() over (partition by emp_name order by Current_Property_value desc)
You can use ROW_NUMBER with CTE.
Query
;WITH CTE AS(
SELECT rn = ROW_NUMBER() OVER(
PARTITION BY emp_name
ORDER BY id_Seq_No DESC
), *
FROM your_table_name
WHERE emp_name = 'John'
)
SELECT * FROM CTE
WHERE rn = 1;

How can I find duplicate on one column

I have a SQL server database,and there are many duplicate in one(RanjePhoneNumber) column.
I am trying to select rows from a table that have duplicates in RanjePhoneNumber column and they have a same CityId.
My Table:
RanjePhoneNumber ContactId CityId
776323 280739 7
342261 186372 80
468284 75980 7
776323 101969 9
362875 170242 13
224519 164914 7
342261 203606 55
776323 280733 7
342261 203602 80
My expected results:
RanjePhoneNumber ContactId CityId
776323 280739 7
342261 186372 80
776323 280733 7
342261 203602 80
Group by those two columns:
SELECT RanjePhoneNumber, CityID
FROM dbo.TableName
GROUP BY RanjePhoneNumber, CityID
HAVING COUNT(*) > 1
If you want to select all columns you could use a ranking function:
WITH CTE AS
(
SELECT t.*, Cnt = COUNT(*) OVER (PARTITION BY RanjePhoneNumber, CityID)
FROM dbo.TableName
)
SELECT RanjePhoneNumber, ContactId, CityId
FROM CTE
WHERE Cnt > 1
If you don't want to find all rows which belong to this "duplicate-group" but only all but the first, use the ROW_NUMBER approach the other answer has shown.
;with cte
as
(select
Ranjephonenumber,
contactid,
cityid,
row_number() over (partition by Ranjephonenumber,cityid order by cityid) as rn
from table
)
select
Ranjephonenumber,contactid,city from cte where rn>1

how to to get first top 6 records indifferent columns T-sql?

I got a situation to display first top 6 records. first 3 records in FirstCol and next 3 in SecondCol. My query is like this:
select top 6 [EmpName]
from [Emp ]
order by [Salary] Desc
Result:
[EmpName]
----------------------
Sam
Pam
Oliver
Jam
Kim
Nixon
But I want the result to look like this:
FirstCol SecondCol
Sam Jam
Pam Kim
Oliver Nixon
; WITH TOP_3 AS
(
select TOP 3 [EmpName]
,ROW_NUMBER() OVER (ORDER BY [Salary] Desc) rn
from [Emp ]
order by [Salary] Desc
),
Other3 AS
(
SELECT [EmpName]
,ROW_NUMBER() OVER (ORDER BY [Salary] Desc) rn
FROM Employees
ORDER BY [Salary] DESC OFFSET 3 ROWS FETCH NEXT 3 ROWS ONLY
)
SELECT T3.[EmpName] , O3.[EmpName]
FROM TOP_3 T3 INNER JOIN Other3 O3
ON T3.RN = O3.RN
ORDER BY T3.RN ASC
You can do this using several windowing functions, this is kind of ugly but it will get you the result that you want:
;with data as
(
-- get your Top 6
select top 6 empname, salary
from emp
order by salary desc
),
buckets as
(
-- use NTILE to split the six rows into 2 buckets
select empname,
nt = ntile(2) over(order by salary desc),
salary
from data
)
select
FirstCol = max(case when nt = 1 then empname end),
SecondCol = max(case when nt = 2 then empname end)
from
(
-- create a row number for each item in the buckets to return multiple rows
select empname,
nt,
rn = row_number() over(partition by nt order by salary desc)
from buckets
) d
group by rn;
See SQL Fiddle with Demo. This uses the function NTILE, this takes your dataset of six rows and splits it into two buckets - 3 rows in bucket 1 and 3 rows in bucket 2. The (2) inside the NTILE is used to determine the number of buckets.
Next I used row_number() to create a unique value for each row within each bucket, this allows you to return multiple rows for each column.

Resources