SQL Server 2014 :: Getting Unique Number For Groups Of Records?

Aug 6, 2014

I'm trying to do the following and haven't been able to figure it out.

Say there's a table with these records:

Col1 Col2 Col3
a b c
a b c
a b d
e f g
e f g

I want to generate a number that represents the groups of columns like this:

Col1 Col2 Col3 MyNumber
a b c 1
a b c 1
a b d 2
e f g 3
e f g 3

So that each grouping gets its own identifier. I've tried this:

SELECT Col1, Col2, Col3
row_number() OVER (PARTITION BY Col1, Col2, Col3
ORDER BY Col1, Col2, Col3) AS MyNumber
FROM MyTable

But I get this:

Col1 Col2 Col3 MyNumber
a b c 1
a b c 2
a b d 1
e f g 1
e f g 2

View 9 Replies


SQL Server 2014 :: Adding Alphabet To A Number To Make It Unique

Nov 25, 2013

create table #temp_Alpha_num (
[uniquenum] [int] Not NULL,
[Somenum] [int] Not NULL,
Insert into #temp_Alpha_num(uniquenum,Somenum)

[Code] ....

For the somenum column I need to add alphabets to make them unique. for example

121a,121b,121c....121z,121aa,121ab,101a and so on...

View 4 Replies View Related

How To Get Unique Records When There Are More Groups

Oct 7, 2005

Steve writes "I need a query to show all the medicare patients only. I want only one kind of insurance for each patient. I am getting records where each patient has more than one insurance like medicare and something else.
Each patient has one,two, three or more insurances like
medicare,medical,blue cross,tricare etc.

The result should look like this:
Sam pick Medicare
John white Medicare
Ann Richmond Medicare

My query retrieves patients with more than one insurance.

select patient_first_name f_name,patient_last_name l_name,patient_zip zip,
count(distinct payer_id) payer_id
from claims
where payer_id ='abcdefhj'
group by patient_first_name, patient_last_name,patient_zip
having count(distinct payer_id)= 1
order by patient_zip asc;

please help me. Greatly appreciate your response."

View 1 Replies View Related

SQL Server 2014 :: Group Up Records Randomly Into N Number Of Batches

Jul 6, 2015

I need to group up the records randomly into ā€˜nā€™ number of batches. That can be done by NTILE, but I want group up similar records in single group.

Say for example, following is the list of records I have in my table which I want to group into 5 batches


After Ntile I will get the below,

Desired output is, Need output like Ntile but all same id should reside in single batch

Even if I n=5, maximum possibility of batches are 3 only.

View 2 Replies View Related

SQL Server 2014 :: Count Duplicate Records Based Upon Account Number?

Jul 16, 2014

I have duplicate records in table.I need to count duplicate records based upon Account number and count will be stored in a variable.i need to check whether count > 0 or not in stored procedure.I have used below query.It is not working.

SELECT @_Stat_Count= count(*),L1.AcctNo,L1.ReceivedFileID from Legacy L1,Legacy L2,ReceivedFiles where L1.ReceivedFileID = ReceivedFiles.ReceivedFileID
and L1.AcctNo=L2.AcctNo group by L1.AcctNo,L1.ReceivedFileID having Count(*)> 0
IF (@_Stat_Count >0)
SELECT @Status = status_cd from status-table where status_id = 10

View 9 Replies View Related

Transact SQL :: Assign Unique Number To Records?

Nov 15, 2015

Lets say I have a table - tblProducts

View 4 Replies View Related

SQL Server Admin 2014 :: CDC And AlwaysOn Availability Groups

Apr 2, 2015

The MSDN doc makes it sound like after a failover of the primary, the CDC data won't "keep working" on the secondary unless you "To allow the logreader to proceed further and still have disaster recovery capacity, remove the original primary replica from the availability group using ALTER AVAILABITY GROUP <group_name> REMOVE REPLICA. Then add a new secondary replica to the availability group."

We have a few CDC tracked tables that we use and the general idea of AlwaysOn I thought was to minimize all the overhead and let things "just work" so your apps just connect and the listener re-routes everything where it needs to go.

It looks like to get this working properly an automated job /trigger would have to wait for a failover event and then kick off tasks to remove and re-add the replica and perhaps start up the CDC job on the secondary?

View 1 Replies View Related

SQL Server Admin 2014 :: Way To Restore All File Groups Except One?

Oct 19, 2015

is there a way to restore all file groups except one? example: Database A has 10 filegroups, but 1 of them is defunct, so i cant delete it and there's no backup for restore it.Can I create a new DB restoring the 9 good FGs from a database A's backup?

View 9 Replies View Related

SQL Server Admin 2014 :: How Does Security Works Between Availability Groups

May 21, 2014

how does security works between availability groups.

ex if i create an object and grant permissions to a user will that be replicated to secondary replica .

View 4 Replies View Related

SQL Server Admin 2014 :: Load Balancing With Availability Groups

Aug 28, 2014

We are having a conversation at work and the subject of load balancing with SQL came up. Right now we are running SQL Server 2014 on four (4) machines. I am using a AlwaysOn with Availability Groups (AG). Now I know that we can scale out the reading in AG by allowing the secondary serves to receive reads.

Is there a way to be able to do this with writes? Can I have in essences 2 masters that some how reconcile with each other? We are expecting a huge amount of writes in the near future and we need a way for SQL to handle the amount of traffic we are expecting with out any issues.

I explored the possibility of Peer - to - Peer replication; however, it seems that it would be more work if we are constantly making updates to the database scheme.

View 2 Replies View Related

SQL Server Admin 2014 :: Backup Jobs On Availability Groups?

Feb 11, 2015

we currently use Backup Scripts from Ola Hallengren, It Says Full (non copy-only) and differential backups are performed on the primary replica. Full(Copy-only) backups and transaction log backups are performed on the preferred replica.

we currently do FULL(COPY_ONLY) Backup everyday and LOG Backups for every 15 min, is there any performance benefit on running the FULL (non copy-only) on the preferred replica .

View 3 Replies View Related

SQL Server Admin 2014 :: Availability Groups - Adding One More Listener

Sep 1, 2015

We have a server A and a server B setup with SQL2014 High Availability - working fine.

I need to add an additional listener to our new DR site.

What is the best way to do this without impacting production - can I just add the additional replica from nodea as a secondary replica?

View 1 Replies View Related

SQL Server Admin 2014 :: Replication On AlwaysOn Availability Groups

Sep 15, 2015

I am planning to have AlwaysON Availability Groups setup between Server 1 and Server 2

Server 1 -->Publisher-->2014 SQL Enterprise edition-->Windows Std 2012 --> Always on Primary Replica

Server 2 -->Publisher(when DR happens)-->2014 SQL Enterprise edition-->Windows Std 2012 --> Secondary Primary

Server 4 as Subscriber

Server X as Remote Distributor ..

If i create Publications on Server1 (primary replica) to subscriber 4 servcer, will the publication be created automatically in Secondary Replica Server2 ? or do i have to create manullay using GUI/T Sql on Both Servers?

View 1 Replies View Related

SQL Server Admin 2014 :: Determine Which Server Is Currently Active For Availability Groups

Nov 25, 2014

I want two write a small script to determine which is the currently active (primary) server in the AG.

Right now, I see that using SELECT * FROM SYS.dm_hadr_availability_replica_states I can determine the role. However, when the server goes down and switches to the secondary node, I don't believe that the role changes (or does it?). How do I determine which is the active node?

View 9 Replies View Related

SQL Server Admin 2014 :: Database Backups And AlwaysOn Availability Groups

Oct 16, 2014

This is my first deployment of an always on availability group for SQL 2014 and I'm trying to get my custom backup procedure to handle all databases appropriately depending on the primary group. Basiscally I want the system databases and all databases that don't participate in the availability group to be backed up on both nodes and those that do participate backed up ONLY on the primary server. I've looked at the sys.fn_hadr_backup_is_preferred_replica funcation, but would like to only have to test for a single databases existance in the availability group. If the one database is in the group, only backup the system databases and those that don't participate, otherwise backup everydatabase. This would be the case for both full backups and transaction logs.

View 1 Replies View Related

SQL Server 2012 :: How To Choose Max Of Each Groups Formed By Row Number

Sep 15, 2015

I have a below table as:

IF OBJECT_ID('tempdb..#Test') IS NOt NULL
--===== Create the test table with
create table #Test([Year] float,
Age Int,
([Year], Age)


I queried below to get additional column

Select *,row_number() over(partition by [Year] order by Age) as RN from #Test as


i want one more addtional column (Desired Output) with max of RN in each group as below"

YearAgeRNDesired output

View 7 Replies View Related

SQL Server 2012 :: Calculate Number Of Groups And Group Size With Multiple Criteria

Jun 15, 2015

I need to calculate the last two columns (noofgrp and grpsize) No of Groups (count of Clientid) and Group Size (number of clients in each group) according to begtim and endtime. So I tried the following in the first Temp table

GrpSize= count(clientid) over (partition by begtime,endtime) else 0 end
and in the second Temp Table, I have
,NoofGrp=count(distinct grpsize)
From Temp1

The issue is for the date of 5/26, the begtime and endtime are not consistent. in Grp1 (group 1) all clients starts the session at 1030 and ends at 1200 (90 minutes session) except one who starts at 11 and end at 1200 (row 8). For this client since his/her endtime is the same as others, I want that client to be in the first group(Grp1). Reverse is true for the second group (Grp2). All clients begtime is 12:30 and endtime is 1400 but clientid=2 (row 9) who begtime =1230 but endtime = 1300. However, since this client begtime is the same as the rest, I wan that client to be in the second group (grp2) My partition over creates 4 groups rather than two.

View 9 Replies View Related

Get Unique Number In Sql Server

Nov 21, 2001


I am new to sql server, in oracle one can get a unique number as:

create sequence my_number
increment by 1 start with 1;

select my_number.nextval from dual;

Is there any similiar mechanism in sql server? if so, how to do it?

THanks in advance,


View 3 Replies View Related

SQL Server 2014 :: Error On Unique Index - Duplicate Key When Insert / Select

Aug 4, 2014

I have an issue where I am getting an error on an unique index.

I know why I am getting the error but not sure how to get around it.

The query does a check on whether a unique value exists in the Insert/Select. If I run it one record at a time (SELECT TOP 1...) it works fine and just won't update it if the record exists.

But if I do it in a batch, I get the error. I assume this is because it does the checking on the file before records are written out and then writes out the records one at a time from a temporary table.

It thinks all the records are unique because it compares the records one at a time to the original table (where there would be no duplicates). But it doesn't check the records against each other. Then when it actually writes out the record, the duplicate is there.

How do I do a batch where the Insert/Select would write out the records without the duplicates as it does when I do it one record at a time.

Name varchar(50),
Email varchar (40)
Insert #TestTable (Name,Email) Values('Tom', 'tom@aol.com')

[Code] .....

View 1 Replies View Related

SQL Server 2014 :: Query To Display Unique Comments Based On Certain Conditions

Jul 1, 2015


Column NameComments


211XYZ 123


211XYZ 123

Records should be filtered by

1.Display only Unique Comments from Customer Table for all the customers,
2.If Comments are same then display the row which has maximum SequenceNo

View 2 Replies View Related

SQL Server 2014 :: Find Views Which Has More Than 16 Columns For Unique Index / Constraint

Oct 27, 2015

We are on SQL 2014...we have a bunch of views in a database where we are trying to find the views which have more than 16 columns max for unique index/constraint...this is needed so we can convert them to indexed views...

View 1 Replies View Related

Transact SQL :: How To Get 8 Digit Unique Number In Server

May 19, 2015

How to Generate the Unique 8 Digit Number in SQL SERVER.And also am trying with below methods which is not working as expected.


DECLARE @UniqueID uniqueidentifier
SET @UniqueID = NEWID()
SELECT LEFT(@UniqueID,8) AS '8DigitUniqNum'

View 9 Replies View Related

SQL 2012 :: Creating A Unique ID For Groups Of Rows?

Mar 20, 2015

We have a sorted data that looks like the first 3 columns below, and fourth colum is what I want to create)

Shift_start meal_break shift_endShift ID
1 0 0 1
0 0 0 1
0 0 1 1

1 0 0 2
0 0 0 2
0 0 1 2

I need to find a method to assign unique Shift IDS to rows that correspond to a single shift. For instance, the first shift would begin on the first row when shift_start flag is turned on, and end on the third row when shift_end flag is turned on.

Can I do this in SQL ?...some kind of grouping ?

View 2 Replies View Related

SQL Server 2014 :: Split Out A Field Of Comma Separated Values Based On Unique Code In Same Row?

Oct 21, 2014

I have a comma separated field containing numerous 2 digit numbers that I would like splitting out by a corresponding unique code held in another field on the same row.


Unique Code Comma Separated Field

14587934 1,5,17,18,19,40,51,62,70

6998468 10,45,62,18,19

79585264 1,5,18

These needs to be in column format or held in an array to be used as conditional criteria.

Unique Code Comma Separated Value

79585264 1

79585264 5

79585264 18

View 5 Replies View Related

SQL Server 2008 :: Run Query To Retrieve 650 Unique Records

May 14, 2015

I've a excel spreadsheet with 650 records with unique PONumbers. I need to pull data from SQL server based on the PONumbers. I don't want to run select statement 650 times. How do I retrieve the records in efficient way?

View 9 Replies View Related

SQL Server 2014 :: ERD - Minimum Number Of Times That R2 Can Appear In Connection?

Dec 14, 2014

I got this ERD and I have 2 questions about it:

What is the minimum number of times that R2 can appear in the connection? and what is the maximum?


View 1 Replies View Related

SQL Server 2014 :: Order By Month Number In A Group By

Dec 19, 2014

Sample Data
USE tempdb;
CREATE TABLE CheckRegistry (
CheckNumber smallint,


How can I get the result orderd by the month number?

View 3 Replies View Related

SQL Server 2014 :: Generate Random Number In Range

Oct 3, 2015

I have a function which generate random number in range :


If you run this script you always get result between 1 and 4

SELECT dbo.Func_Rand(4, NEWID())

BUT, in this script sometimes have no result !!!!!!! why??

WHERE dbo.Func_Rand(4, NEWID()) IN ( 1, 2, 3, 4 )

View 2 Replies View Related

SQL Server Admin 2014 :: High Number Of VLFs

Oct 7, 2015

I have heard that high numbers of VLF's aren't good. It can impact performance and can delay recovery time, so I wanted to test that.

I created 2 DBs with 100MB datafile and 50MB logfile.

TestDB log file had 100MB autogrowth
TestDB2 log file had 1% growth.

I inserted 1048576 records, took the backup

Ran DBCC loginfo and
TestDB had 40 VLFs and
TestDB2 had 165 VLFs

But when I restored both DBs, this is what I got.

RESTORE DATABASE successfully processed 42258 pages in 4.420 seconds (74.691 MB/sec).
SQL Server Execution times:
CPU Time = 125ms, elapsed time = 8323 ms.

RESTORE DATABASE successfully processed 42257 pages in 3.943 seconds (83.724 MB/sec).
SQL Server Execution Times:
CPU time = 109 ms, elapsed time = 8314 ms.

Question is: Where is the difference? How TestDB which has 40 VLFs are better than TestDB22 which has 165 VLFs.

View 6 Replies View Related

SQL Server 2014 :: Selecting Records From Table 2 While Counting Records In Table 1

Aug 11, 2015

Table1 contains fields Groupid, UserName,Category, Dimension

Table2 contains fields Group, Name,Category, Dimension (Group and Name are not in Table1)

So basically I need to read the records in Table1 using Groupid and each time there is a Groupid then select records from Table2 where Table2.Category in (Select Catergory from Table1)
and Table2.Dimension in (Select Dimension from Table1)

In Table1 There might be 10 Groupid records all of which are different.

View 9 Replies View Related

SQL Server Admin 2014 :: How To Get Number Of Execution In Specific Time - Not From First

Apr 7, 2015

I have this query

SELECT top 100 Ltrim([text]),objectid,total_rows,total_logical_reads , execution_count
FROM sys.dm_exec_query_stats AS a
CROSS APPLY sys.dm_exec_sql_text(a.sql_handle) AS b
where last_execution_time >= '2015-04-07 10:01:01.01'
ORDER BY execution_count DESC

But the result of execution count is from the first. I want to know it only one day.

View 9 Replies View Related

SQL Server 2014 :: Huge Number Of Rows In Table Spool

Jul 6, 2015

I have a CTE query against a table with 32K rows that runs fine in 2008R2. I am running it in 2014 Std Ed. against the same data and it runs very slowly. Looking at the execution plan I think I see what's contributing to the slowness.

Note that the "actual number of rows" is some 351M...how is this possible?

the query:

declare @amts table (claim int,allowed decimal(12,2),copay decimal(12,2),deductible decimal(12,2),coins decimal(12,2));
;with unpaid (claimID) as (select claimID from claim where amt+copay + disct+mm + ded=0)
insert @amts
select lineID, sum(rc), sum(copay), sum(deduct),
case when sum(mm)>0 and (sum(mm)<sum(mmamt)) then sum(mm) else 0 end
from claimln
where status is null
and lineID not in (select claimID from unpaid)
group by lineID

it's like there's some massively recursive process going on?

View 5 Replies View Related

SQL Server 2014 :: Incrementing Number In Table And Then Resetting Column

Jul 15, 2015

I have four columns in my table, the first one is the identity column

col1 Col1 col2 col3

1 12 1 This is Test1
2 12 2 This is Test1
3 12 3 This is Test3
4 12 4 This is Test4
5 12 5 @@@@@

When, I see, @@@ sign in my col4, I need to restart the col3 from 1 again so it will look like this

col1 Col2 col3 col4

1 12 1 This is Test1
2 12 2 This is Test1
3 12 3 This is Test3
4 12 4 This is Test4
5 12 5 @@@@@
6 12 1 This is another test1
7 12 2 This is another Test2

Is it possible to do that?

View 8 Replies View Related

Copyrights 2005-15 www.BigResource.com, All rights reserved