Transact SQL :: Unique Pairs Of Data?

Sep 23, 2015

In my table, I have some duplicate rows. I want to select only the unique value pairs.

So, the table/data look like this:

ColumnA  -- ColumnB
123  -- 234
234  -- 345
234  -- 345
345  -- 456

I want to create a select statement that will only return:

123  -- 234
234  -- 345
345  -- 456

In other words, the duplicate row i.e. the second 234 - 345 -- won't be included in the set my SELECT statement will return.

View 2 Replies


ADVERTISEMENT

Select Unique Country / Date Pairs With Self Join

Sep 16, 2013

I have built a sample table, query, and results for this question. I am using SQL server.

declare @TableX Table
(
Date Date not null,
ID int not null,
Tick varchar(6) not null
)
INSERT @tableX

[Code] ....

Expected results:
DATE(No column name)count
2013-09-02LON1
2013-09-03LON1
2013-09-04LON1
2013-09-05LON1
2013-09-06LON1
2013-09-02USA2
2013-09-03USA2
2013-09-04USA2
2013-09-05USA2
2013-09-06USA2

I want to select unique country - date pairs. It is not even necessary to have the count of each one, just the list of unique country/dates.

My query here uses 'group by' to accomplish this task, but there may be a way to do this with a self join. I believe using a self join would make the query faster.

1) Is this possible to do with a self join?

View 2 Replies View Related

Transact SQL :: Generate Unique Username From Data Columns

Oct 19, 2015

I am trying to achieve the below problem statement, however I am getting stuck at the looping part.

EX: We have three columns

First Name |  Last Name | Mothers Name

I want to generate the username field using above columns, so lets consider, I have following data

First Name |  Last Name | Mothers Name
a                    b                  cdef
a                    b                  cdfg
a                    b                  cdfj

Expected Usernames:

1: a.b
2: a.b.c
3. a.b.cd

Basically, it has to be FirstName.LastName.(incremental letters from MothersName until the name becomes unique)

View 4 Replies View Related

Parsing CSV Name=value Pairs Into Columns

Nov 7, 2006

Hello smart SQL people,

I have a field in the DB that contains name value pairs in the form of csv. Is there a neat trick (using a stored proc) to get it to be diplayed as in columns (maybe create a view around it or somthing?) ?

EX.

Select 'name1=val1;name2=val2;name3=val3' as MyData

--> Returns
MyData
-----------
name1=val1;name2=val2;name3=val3

============================================

How can i get it to return

name1 name2 name3
--------------------------------
val1 val2 val3

View 9 Replies View Related

Transact SQL :: Set Unique Random Number

Dec 1, 2015

Lets say we have a table (tblProducts)

ID   Item             RandomNumber
-------------------------------------------
1    JEANS                      1234567
2    SHIRT                    72813550
3    HOOD                             Null
4    TROUSER               72191839
5    BLAZER                              0

I want to perform a query so that SQL should look for RandomNumber Values and set a Unique Random Number Where RandomNumber Value is Null or 0.So I have got a solution as one of the MSDN Member shared the below query

select id,item,RandomNumber=Case when RandomNumber=0 then (select floor(rand()*100000000-1))
when RandomNumber is null then (select floor(rand()*100000000-1))
else RandomNumber end from tblProducts

So, can you all confirm me, that performing this query ensures that if a Value is assigned to one of the Item in RandomNumber Column, that value will not be assignend to any other Item in RandoNumberColumn.

View 15 Replies View Related

Transact SQL :: Merge With Unique Identifier As PK

Jul 2, 2015

Using SQL Server 2014 i try to merge data from database [Susi] on server2 to database [Susi] on server1. Server2 is a linked server in server1. The PK of the table Core.tKontakte is uniqueidentifier with rowguidcol.

I wrote the following script and get error 206: "uniqueidentifier ist inkompatibel mit int".

    INSERT Core.tKontakte (KontaktID, AnredeID, Titel, Nachname)
    SELECT KontaktID, AnredeID, Titel, Nachname
    FROM [Susi].MSCMS.Core.tKontakte AS Client
    WHERE NOT EXISTS (SELECT KontaktID FROM Core.tKontakte AS Host WHERE Host.KontaktID = Client.KontaktID);

[Code] ....

View 8 Replies View Related

Transact SQL :: Need Of Primary Key If Everything Can Be Achieved By Unique Key?

Oct 13, 2015

What is the need of Primary Key if everything can be achieved by Unique Key? Everything that primary key does, Unique key can also fill those things.Why primary key is required?

View 4 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

Transact SQL :: Efficient Way To Calculate Unique Values?

Jul 14, 2015

I have a data set as -

ID       Set Date          DB Date
100     Null                 07/01/15
100     07/05/15         07/02/15
100     07/10/15        07/08/15

I want to able to get 2 unique dates

1. 07/02/15 - As I want the DB date for ID - 100 when set date changed from a null value to non null value.

2. 07/08/15 - As I want the DB date for ID - 100 when a non null set date changes.

The table has such records for lot of different ID's.

View 29 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.

Methode-1:
SELECT CONVERT(VARCHAR(5),GETDATE(),112) +CONVERT(VARCHAR,DATEPART(MS,GETDATE())) AS '8DigitUniqNum'

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

View 9 Replies View Related

Transact SQL :: Insert Unique Values Only Using MERGE

Jun 2, 2015

I'm trying to use merge data from a staging table to a production table. There are a lot of duplicate values for serverName and I only want to insert one instance where there are duplicates.

How I can adapt the code I have so far to achieve this?

MERGE tblServer AS TARGET
USING tblTemp AS SOURCE
ON (TARGET.serverName = SOURCE.serverName)

WHEN MATCHED THEN
UPDATE SET TARGET.serverName = SOURCE.serverName, TARGET.serverLocation = SOURCE.serverLocation

WHEN NOT MATCHED BY TARGET THEN
INSERT (serverName, serverLocation)
VALUES (SOURCE.serverName, SOURCE.serverLocation)

WHEN NOT MATCHED BY SOURCE THEN
DELETE;

View 3 Replies View Related

Transact SQL :: How To Find Combination Of Column - Row Unique

Mar 8, 2012

I have table with some columns with no primary key..

I have to find the combination of columns which may the row unique...

How to do that like microsoft...

View 14 Replies View Related

Storing Large Arrays Of Ordered Pairs

May 13, 2008

How do you all recommend storing ordered pairs in SQL Server 2005? I plan to add one record for every data point but this will generate many records and requires an extra field to relate the points together. Are there any better ways to do this? Can the data still be searchable or does it have to be unpacked first?

View 2 Replies View Related

Transact SQL :: UPDATE Statement Failing On Unique Key Constraint

Jul 9, 2015

I'm trying to update rows in a simple table that has a UNIQUE KEY CONSTRAINT defined on one of its columns. Here is the DDL for the table:

CREATE TABLE [dbo].[SEC_USER](
 [SEC_USER_ID] [int] IDENTITY(1,1) NOT NULL,
 [USER_CODE] [varchar](100) NOT NULL,
 [USER_NAME] [varchar](128) NOT NULL,
 [EMP_CODE] [varchar](6) NOT NULL,

[Code] ....

When trying to execute the UPDATE statement the query fails with a constraint violation error:

Violation of UNIQUE KEY constraint 'UQ__SEC_USER__A039F1EE62FE8444'. Cannot insert duplicate key in object 'dbo.SEC_USER'. The duplicate key value is (34337).

What has  me baffled is that I'm not doing any insert. Also, the value that it's referencing - 34337 - doesn't exist in the table at all. I'd rather not drop the constraint.

View 8 Replies View Related

Transact SQL :: Select Unique From Table If Specific Value Does Not Exists

Jul 31, 2015

I have a table that has for each shop a value that can change over time.For example

BK_POS 1 --> Segment A
BK_POS 1 --> Segment /

What I would like to achieve is to get all distinct Shops (BK_POS) from the table above, but if for that specific pos a row exists where the segment = "/" then I do not want to take this BK_POS in my select query.More concrete, the for example above I do not want to select BK_POS 1 because he has one row where the segment = "/".

View 3 Replies View Related

Transact SQL :: Create Unique ID Based On Existing Fields

Sep 1, 2015

I have the following table (Table does not have unique key id )

Last Name     First Name         DATE        Total-Chrg

Jaime               KRiSH           5/1/2015         -4150.66
Jaime               KRiSH           5/1/2015          1043.66
Jaime               KRiSH           5/1/2015          1043.66
Jaime               KRiSH           5/1/2015           4150.66
Jaime               KRiSH           5/3/2015           4150.66
Peter                Jason            5/1/2015           321.02
Peter                Jason            5/1/2015           321.02
Peter                Jason            5/23/2015         123.02

I want the results to be in following way

Uniq ID    Last Name    First Name          DATE         Total-Chrg

1                Jaime            KRiSH                 5/1/2015     -4150.66
2                Jaime            KRiSH                 5/1/2015     1043.66
2                Jaime            KRiSH                 5/1/2015     1043.66
3                Jaime            KRiSH                 5/1/2015      4150.66
4               Jaime             KRiSH                 5/3/2015      4150.66
5               Peter              Jason                5/1/2015       321.02
6               Peter              Jason                5/1/2015       321.02
7               Peter              Jason               5/23/2015     123.02

May be we may do by dense_rank or Row_Number, but I couldn't get the exact query to produce based on the above table values.  There are some duplicates in the table(which are not duplicates as per the Business). For those duplicated Unique ID should be same(Marked in Orange Color which are duplicates). 

View 4 Replies View Related

Transact SQL :: SELECT Unique Values In Single Column?

Jun 8, 2015

I have the following two tables...

tblServer
-serverID
-serverName
-serverLocation
tblSite
-siteID
-serverID
-siteName
-siteIpAddress

I need to write a select query that gets the values of all columns but only returns unique sites because some sites are load balanced across several servers and where this is the case I don't want the site to appear multiple times in the list.

View 4 Replies View Related

Transact SQL :: Update Unique Records Count For Subquery?

Sep 2, 2015

updating the # of Payer from below query to match with the # of rows for each payer record. See the Current and desired results below. The query is currently counting the # of rows for all payers together and updating 3 as # of payers. I need it to count # of rows for each payer like shown inDesired result below. It should be showing 1 for first payer and 2 for 2nd & 3rd based on # of times each payer is repeated..

SELECT b.FILING_IND, b.PYR_CD, b. PAYER_ID, b. PAYER_NAME,a.CLAIM_ICN,
(Select Count(*) From MMITCGTD.MMIT_CLAIM a, MMITCGTD.MMIT_TPL b , MMITCGTD.MMIT_ATTACHMENT_LINK c where a.CLAIM_ICN_NU =
c.CLAIM_ICN and b.TPL_TS = c.TPL_TS and a.CLAIM_TYPE_CD = 'X' 

[Code] ....

Current Result

FILING_IND
PYR_CD
PAYER_ID
PAYER_NAME
CLAIM_ICN
#_OF_PAYER

[code]....

View 4 Replies View Related

Transact SQL :: Creating A View Using DISTINCT And Not Getting Unique Results?

Sep 21, 2015

I am building a view to be used to drill down into a Lightswitch app I'm building and to drive this I want to use a view based off the selection of that value several other values will be given to the user to choose from related to the first selection. I've created a view using the following statement:

SELECT DISTINCT TOP (100) PERCENT ARSFamily, ARS_Index
FROM dbo.csr_standards_cmsars
ORDER BY ARSFamily

 but the results come back with ALL the records of the source table (509 rows) when there should have only been 29 rows returned (the appropriate number of families or unique groups).  The index is necessary to have Lightswitch use the view as a data source.what I'm doing wrong here?

View 2 Replies View Related

Transact SQL :: How To Compare Duplicate Rows Within A Unique Process

Nov 9, 2015

We write to a log file each time a job runs. We give each job a unique batchid. I want to compare the run times of each step/record between two batch ids: '20150101888' and '20150101777'. Column Mins in the number of minutes each step ran. I am having trouble comparing the rows that have generic process and stepname – Trans Switch in this example. A new process within a batchid starts with a 'XX', 'Load'.

So I want to compare CA's Trans to CA's Tran Switch and ER's Trans Switch to ER's, etc. There can be multiple Trans Switch per process. There should be the same number between each batch, but no guarantees that  something might change. Also, Trans Switch is not the record right after the new process (CA, ER) in production.

I have just made a very simplified example.

/**
Want to compare 20150101888 to 20150101777 and end up with this result set. Notice that the duplicate process/step within a process has the process (CA and ER in this example) and a sequential number added to it: 'CA Trans 1'. Need this to pull out the largest time differences.

Time difference, process, step, mins1, mins2, batchid1, batchid2
-6, CA, Load, 17, 23, 20150101888, 20150101777
0, CA Trans 1, Switch, 8, 8, 20150101888, 20150101777
-6, CA Trans 2, Switch, 9, 15, 20150101888, 20150101777
-4, ER, Load, 7, 11, 20150101888, 20150101777
-4, ER Trans 1, Switch, 7, 11, 20150101888, 20150101777

**/

[Code] ....

View 4 Replies View Related

String Parsing - Grab Some Key Value Pairs From Text In Column

Jul 21, 2014

I want to grab some key value pairs from the text in sql column

e.g.

some text[Key1=Val1]some text[Key2=Val2][Key3=Val3]some text

I want a function which takes Keyname as input & returns the value related with it if found.

GetValueFmKey('Key1') should return Val1 and like on.

View 1 Replies View Related

Reconcile Pairs Of Parent-Child Items. Ideas Please?

Feb 15, 2008

I need ideas on how to achieve the following:

A parent can have many children - always has at least one.

A parent always has an 'anti-parent' with an equal number of 'anti-children' to the normal parent

Each child and anti child has a unique ID


I need to reconcile each Parent/antiParent Child/antichild and highlight the differences before.

Normally, reconciliation reports are fairly straightforward due to the fixed number of items, I'm not quite sure of the best way to do this.


How it should look in the report

PARENT A field1,field2,...,field n
PARENT B field1,field2,...,field n
CHILD A1 childfield1,cf2,....cf n (child A1 and B1 share a unique ID)
CHILD B1 childfield1,cf2.....cf n
CHILD A2
CHILD B2
...
CHILD An
CHILD Bn


So, compare PARENT A with PARENT B and highlight any differences
compare CHILDA1 with CHILD B1 and highlight any differences
...
compare CHILDAn with CHILD Bn and highlight any differences

Thoughts?

View 2 Replies View Related

Transact SQL :: Finding Unique Counts Based On Consecutive Days?

Jul 9, 2015

I have a scenario here where the data looks like -

ID        Date
100      07/01
100     07/02
100    07/03
100   08/01
100   08/02
100   08/15

Now I need to find out unique occurrences of ID - 100 ( where count = unique only if the occurrences are in consecutive days, gap of even 1 day causes it to be a different instance ) - SO with the above data I should have unique occurrences as 3.efficient way to calculate this ?

View 5 Replies View Related

Transact SQL :: ORDER BY Clause Is Ignored When A Unique Index On Criteria Columns Exist

Sep 16, 2015

In SQL 2012.A query that joins 2 table, with order by clause doesn't get sorted and the result set is not ordered. This happens when some of the columns in the where criteria are in a unique index which is the index that is used for the join between the 2 tables, and all the columns in the unique index are in the where criteria.In the query plan there is no component for sort.The work around was to drop the unique index, or change it to a non-unique index. Once this was done, the execution plan was changed to add the sort component (even when the index was changed to non-unique and the join was still using this index).

View 4 Replies View Related

Delete Rows With Duplicate Column Data But Unique Row Data

May 25, 2000

Hello,

This probably has been addressed before but I was unable to get the search to work properly on this site.
I am needing a script/way of deleting all rows from a DB with the exception of one record left for each row that has duplicate column data. Example :
Row 1
Field1 = 12345 Field2 =xxxxx Field 3=yyyyy Field4=zzzzz etc.
Row 2
Field1 = 12345 Field2 =zzzzzz Field 3=xxxxxx Field4=yyyyyy etc.
Row3
Field1 = 12345 Field2 =20202 Field 3=11111 Field4=zzzzz etc.
Row 4
Field1 = 54321 Field2 =xxxxx Field 3=yyyyy Field4=zzzzz etc.
Etc. Etc.

I want to be able to find the duplicates for Field1 and then delete all but 1 of those rows.( I don't care which one I keep just so only one is left.) The data in the other fields may or may not be unique.

I know how to find the duplicates it's just the deleting part I am having problems with. Any help would be much appreciated. Thanks,

Kerry

View 3 Replies View Related

Import Data Where Current Data Has Unique Identity

Aug 10, 2000

I have data for online catalogue in SQL 7.0. The web grogrammer asked me to add a unique key for reference. I used int datatype with identity seed of 1 and increment of 1. This works fine BUT when I try to import new data I get an error because the csv file has no column and therefore no value for the unique field which will not allow null by definition.

How can I maintain a unique field to act as primary key in my data when
I want to add (and delete) data that doesn't have this field.

I tried adding the uniqueidentifier field but this gives error message.

The only work round is to delete the unigue field altogether and then add the new data and afterwards create a new unique field. At 600000 + lines of data, this is time and memory consuming

Any help appreciated,Thanks, Keith

View 1 Replies View Related

Transact SQL :: Establishing Unique Sales ID To Future Sales IDs From Original Sale

May 19, 2015

i am trying to find a way to link an 'initial' Sale ID of a product to 'future' Sale IDs of products that will trace back to the original Sale ID.For example, if I call the original sale , 'Sale ID #123',  how can i link future Sale ID's (child[ren]) and all future sales to the original Sale ID #123? Can I use a Surrogate Key or similar function?

Parent:Sale ID #123
Children: Sale ID # 456,
Sale ID #789,
Sale ID #.....

how I can link the original Sales ID (Parent) to Sale ID's (child[ren]) of future purchases currently existing and in the future going forward?

View 4 Replies View Related

Transact SQL :: Find Unique Rows In Column That Are Associated With Another Field In Another Column?

May 1, 2015

I am having issues trying to write a query that would provide me the unique GUID numbers associated with a distinct PID if the unique GUID's > 1.  To summarize, I need a query that just shows which PID's have more than one unique GUID. A PID could have multiple GUID's that are the same, I'm looking for the PID's that have multiple GUID's that are different/unique. 

Table1

GUID PID
GUID1 PID1
GUID1 PID1
GUID1 PID1
GUID2 PID1
GUID3 PID2
GUID3 PID2
GUID3 PID2

The result of the query would only have PID1 because it has two unique GUID's. PID2 would not be listed has it has the same GUID3 in each row.

Result:

PID1 

View 2 Replies View Related

Importing Unique Data && MAX Data To Table Using DTS

Nov 28, 2005

I am creating a DTS package that is combining several tables, converting one column of data to a new column removing all special characters, then exporting the unique data based on this column and another column, and the max of other duplicates to a new table.

Now that I have the data in this table, I want to import any data that is not in my main table.

This "CLEANED" table does not have a designated "key" column, but the table I want to import the unique items does have an ID column that is also a primary key column.

DTS seems to want me to have a Key column to reference when importing from the CLEANED table to the MAIN table.

How would I go about checking the MAIN table against the CLEANED table, having DTS import only the unique items from the CLEANED table that are not present in the MAIN table based on three columns? The rest of the columns I want to just extract the MAX data from the duplicates.

Now here is the query I use to extract the unique values from the "CLEANING" table to get the data to the "CLEANED" table, but do not know how to use this to import into the MAIN table using something similar.


Code:



select
partno2,
MAX (partno) as partno,
alt,
MAX (C_alt) as C_alt,
Max (cmpycd) as cmpycd,
MAX (type) as type,
compFN,
MAX (pndesc) as pndesc,
MAX (equipment) as equipment

into tbl_CLEANED
from tbl_CLEANING
group by partno2, alt, compFN
ORDER BY partno, compFN



The three main columns I need to check against are:
partno2
alt
compFN
I have named the columns the same in both tables.

partno2 is the column that has been copied from partno with all special characters & spaces removed. This is the main column I am using as a reference for unique values, then if no match, I have it check against the alt column, then the comFN column. If there are no matches in any of these columns, then I want to extract the data to the MAIN table.

How can I compare these tables and import only unique info to the MAIN table?

In addition, how can I also check items that are the same in both tables and update the MAX info for the other columns (not the three I use for reference - these I need to leave alone) and update those if there is more data in the CLEANED table then in the MAIN table?

View 3 Replies View Related

Indexing Non-unique Data

Mar 31, 2006

I have two tables which are related. The first table(A) has a sequentially assigned unique key (primary) that has a cluster index built on it. This table has roughly 1,000,000 rows of data and grows daily.

The second table(B) has a sequentially assigned unique key (primary). There is a column in table(B) which contains table(A)'s unique key. For each row in the table(A) there are roughly 30 rows in table(B).

Should I build a clustered index on the table(B) column which contains the key to table(A) or a non-clustered index?

View 6 Replies View Related

Unique Column Data

Jan 22, 2008

Absolute SQL Beginner here

I am using SQL Server 2005 Express Edition in conjunction with asp.net 2.0

Is there any way to guarantee when INSERTing data, that all values in a given column (which is of a char data type) are unique? Or do I have to do this programatically at the asp layer?

Thanks in advance

Larry

View 4 Replies View Related

SQL Server 2012 :: Failing On Update With Unique Index Error (Not Unique)

Jul 5, 2015

This index is not unique

ix_report_history_creative_id

Msg 2601, Level 14, State 1, Procedure DFP_report_load, Line 161
Cannot insert duplicate key row in object 'dbo.DFP_Reports_History' with unique index 'ix_report_history_creative_id'.

The duplicate key value is (40736326382, 1, 2015-07-03, 67618862, 355324).
Msg 3621, Level 0, State 0, Procedure DFP_report_load, Line 161

The statement has been terminated.

Exception in Task: Cannot insert duplicate key row in object 'dbo.DFP_Reports_History' with unique index 'ix_report_history_creative_id'. The duplicate key value is (40736326382, 1, 2015-07-03, 67618862, 355324).

The statement has been terminated.

View 6 Replies View Related

Unique Rows Of Data Query

Sep 21, 2006

How would I get the unique email addresses and its associated row of data from a SQL Server table that has no unique fields defined? If there is a duplicate email address then only show the first one and not the other rows with the same email address. Example table and data UserID             LastName        Email997249            MCCO-49       S.MCCO-49@SampleISD.org997462            BATE-62         A.BATE-62@SampleISD.org997605            DENS-05        B.DENS-05@SampleISD.org  997622            KAIS-22         A.KAIS-22@SampleISD.org997623            KAIS-22         A.KAIS-22@SampleISD.org997624            KAIS-22         A.KAIS-22@SampleISD.org997625            KAIS-22         A.ZKAIS-22@SampleISD.org997626            KAIS-22         AX.ZKAIS-22@SampleISD.org997627            KAIS-22         AX.KAIS-22@SampleISD.org   Result UserID             LastName        Email997249            MCCO-49       S.MCCO-49@SampleISD.org997462            BATE-62         A.BATE-62@SampleISD.org997605            DENS-05        B.DENS-05@SampleISD.org  997622            KAIS-22         A.KAIS-22@SampleISD.org997625            KAIS-22         A.ZKAIS-22@SampleISD.org997626            KAIS-22         AX.KAIS-22@SampleISD.org Thanks

View 13 Replies View Related







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