Join To Show One Row Per Unique Record

Apr 23, 2015

I am new to SQL but trying to do join a few tables to get result showing showing one row per unique record.

Tables include:-

1. REQ
2. RFQ
3. PO
4. DOCUMENT (contains LAST_DOCUMENT_STATUS, DOCUMENT_ID, DOCUMENT_NUMBER, for example, REQ_CANCELLED, REQ_ID, REQ_NO)
5. DOCUMENT_STATUS (contains status of document, REQ_CREATE)
6. DOCUMENT_TRAIL (contains link between documents, PARENT_DOCUMENT, CURRENT_DOCUMENT, for example, REQ_ID (PARENT_DOCUMENT), RFQ_ID (CURRENT_DOCUMENT)
7. PO_REVISION (contains PO REVISION, when link with DOCUMENT, PO_REV_NO)

Currently when i tried to join all the TABLES, i get multiple lines against REQ_NO.

I realised the multiple lines generated due to the following:-

One to many relationships:
A. RFQ - 1 or more PO
B. PO - 1 or more PO_REVISON

I was thinking how to MAX the records in PO to show only the last PO_REVISION. It seems that DOCUMENT_TRAIL will contain 1 base document PO and 1 or more PO_REVISION.

View 13 Replies


ADVERTISEMENT

Filter One Record, Show The Others.

May 6, 2005

Hi,

I've got a question...

sample record x
id field1 field2
1 a q
2 b x
3 a y
4 b z

I want to set a "y" filter on field2 but want to have all records with the same field1 value as result.

so, in the field2 = "y" filter, I want record 1 and 3 as result because field1 is in both records "a"

(Show me all records with the same Field1 value when field2 is y)

Is this possible and if so, how?

Kind regards,

Emiel Romein
Netherlands, the

View 3 Replies View Related

How To Show One Record Per One Page

Sep 27, 2007



I am using reporting services to build a report to show customer's balance statements. I need each page only show one customer and related transactions and balance etc.

Now it shows several customers' balance in one page, how can i change it to show only one record per one page, and also one customer per one page when print it out.

how can i achieve that?

cheers

View 5 Replies View Related

Unique Record

Oct 24, 2005

HI

I HAVE THREE TABLE GEN, PARTY, TXN (GEN & PARRTY IS MASTER TABLE AND
TXN IS TRANSACTION TABLE)
IN TXN TABLE - STORE ALL DATA IN WHICH SAME VOUCHER NUMBER IS REPEATED
ACCORDING TO JOURNAL ENTRY)
NOW PROBLEM IS THIS AT THE TIME OF DISPLAY THE RECORD ON SCREEN I HAVE
TO SHOW ONLY THE UNIQUE VOUCHER NUMBER ONLY..

PLS GUIDE IN THIS QUERY HOW CAN I GET THAT RESULT.


SELECT DISTINCT TXN.VOUCHER, GEN.GLNAME, PARTY.PARTYNAME, TXN.DOCDATE, TXN.GLCODE, TXN.PARTYCODE, TXN.AMOUNT, TXN.VTYPE, TXN.CBCODE, TXN.ADJ, TXN.DC, TXN.NARR
FROM (TXN LEFT JOIN GEN ON GEN.GLCODE=TXN.GLCODE) LEFT JOIN PARTY ON PARTY.PARTYCODE=TXN.PARTYCODE
WHERE TXN.VTYPE='JV'
ORDER BY TXN.VOUCHER


THANKS

ASM

View 3 Replies View Related

Show One Record If Table Is Empty

Apr 25, 2014

I have a query

select salesId,count(*) from salesline group by salesid

Result will be

salesid Nos
----- ---
SO001 2
SO002 4

I want to display single record like below if there is no record available in the table

salesid Nos
So00? 0

View 1 Replies View Related

Unique Record Id Type

Jan 9, 2008

I am trying to make a where clause using the sql server unique record id that is set automatically when a record is inserted. It is the record id that is unique for one table.
In a where clause. What type should go where the _______ is below?
 Here is the program
<%@ page language="vb" %><%@ reference page="try7.aspx" %><% @import namespace="system.data"%><% @import namespace="system.data.sqlclient"%>
<html>   <head>      <title>      </title>      <script language="vb" runat="server">         sub page_load(sender as object,e as eventargs)            response.write(request.queryString("a"))            response.write(",")            response.write(request.queryString("b"))            get1.text=request.queryString("b")         end sub
         sub star(sender as object,e as eventargs)            dim connection1 as new sqlconnection("")
            const q1 as string="update tbltest set code=@code where dxid=@dxid"            dim command1 as sqlcommand=new sqlcommand(q1,connection1)            command1.parameters.add("@code",sqldbtype.varchar).value=get1.text            command1.parameters.add("@dxid",sqldbtype._________).value=request.queryString("a")
            command1.connection.open()            command1.executenonquery()            command1.connection.close()         end sub      </script>   </head>   <body>      <form runat="server">         <asp:textbox id="get1" columns="6" maxlength="6" runat="server" />         <asp:button id="buttonsave" text="click" onclick="star" runat="server" />      </form>   </body></html>

View 3 Replies View Related

How To Get Unique Record With Columns

Mar 20, 2013

I have result set as the attached in screenshot, where the candidateid gets duplicated, but then the column university and careerchoice column has different values for the same candidate. (the CareerChoice and University comes from different tables and i have used union clause)

What want is e.g. CandidateId 186 repeats three times, it should be one row, with three columns all filled with the values which are in different rows.

So that I don't have duplicate candidate ids and i have single row with all column data.

View 6 Replies View Related

Selecting Unique Record

Jul 20, 2005

I have a stored procedure (below), that is supposeto get a Reg Number from a table, (Reg_Number), insuch a way that every time the stored procedure is called,it will get a different reg number, even if the storedprocedure is called simultaneously from two differentplaces,However it is not working that way.If two different users access a function in thereVB program at the same time, the two different userswill get the same reg number.I have looked at the stored procedure, it looks foolproof,yet it is not working that way.Thanks in Advance,Laurence NuttallProgrammer Analyst IIIUCLA - Division of Continuing Education'---------------------------------------------------------------------------Here it is:CREATE PROCEDURE sp_GetNextRegNum@newRegNum char(6) = NULL OUTPUTASLABEL_GET_ANOTHER_REG:Select @newRegNum =(select min(Reg) from reg_number)IF Exists (select Reg from reg_number where reg = @newRegNum )BeginDelete from reg_number where reg = @newRegNumIF @@Error <> 0BeginGoto LABEL_GET_ANOTHER_REGEnd--EndifEndELSEGoTo LABEL_GET_ANOTHER_REG--EndifGO

View 6 Replies View Related

How To Show Records With JOIN?

Apr 5, 2007

Hi ,

I've got two tables.. the first table carried a ProductID, and amongst other things a TradePrice



The other tbl carries a ProductID, a IndivPrice and a CustomerID



The second tbl lists prices for products for indiv Customers.





My Query needs to bring back ALL the products from the first tbl...

It also needs to show the TradePrice for that product.



I need to join my query to the second tbl...



And finally, if the second tbl has a price for that product AND the customerID is the same as one I pass into the query.. show that price also..



So here's my first query:

SELECT dbo.Products.ProductID, ProductName, ProductTradePrice, IndivPrice, dbo.Trade_PriceLists.CustomerID AS PLCustomerID FROM dbo.Products LEFT OUTER JOIN dbo.Trade_PriceLists ON dbo.Products.ProductID = dbo.Trade_PriceLists.ProductID WHERE (ProductType = 'Trade' OR ProductType = 'Both') AND (Replace(Lower(ProductBrand),' ','') = 'brandname') AND (CustomerID IS NULL OR CustomerID = 'teste' OR CustomerID = '') ORDER BY TradeOrder



I thought that would work, but what happens is that, if that particular customer has no indiv prices set.. then it only shows the ones that have no records at all in that second tbl..



So unless there is a record for a particular product in that second tbl and it doesn't have a CustomerID assigned to (which would never happen as that tbl is only every for indiv customer prices) then it doesn't show.





Examples:



First Tbl

ProductID Name TradePrice

1 Jumper £1.00

2 Jeans £3.00

3 Shoes £5.00

4 Hat £2.00



Second Tbl

ProductID CustomerID IndivPrice

1 teste £0.50

2 othercustomer £2.50

3 teste £4.50



What I want in the results is:



ProductID ProductName TradePrice IndivPrice CustomerID (PLCustomerID)

1 Jumper £1.00 £0.50 teste

2 Jeans £3.00

3 Shoes £5.00 £4.50 teste

4 Hat £2.00



See? - The 2nd product should not get an indiv price as although it's in that second tbl, the customerID assigned to it is different. The 4th product should not get an indiv price as it's not in that second tbl at all.



however, with my query above I'd only get Products 1and 3... and if I did a query on a customer with no indiv prices I'd only get product 4 as it's not in the indiv at all...



HELP!!!!!









View 11 Replies View Related

Generate Unique Numbers For Each Record

May 1, 2008

Hi

I am using sqlserver 2005 and want to generate unique numbers for all the records in a table using sql.

Something like table A has



FRUITS
-------------
Oranges
Mangoes
Apricots
....



I want to write a sql query that does something like

SELECT convert(varchar(8),getdate(),12)+'000001' my_number,
fruits
from table A

so the output is


my_number Fruits
080501000001 Oranges
080501000002 Mangoes
080501000003 Apricots
....


regards
Hrishy

View 4 Replies View Related

How To Combine 2 Records Into 1 Unique Record

Jul 11, 2006

Hi all,We have an app that uses SQL 2000. I am trying to track when a code field(selcode) is changed on an order which then causes a status field (status)to change. I tried a trigger but the app may use 2 different updatestatements to change these fields depending on what the user does. When thetrigger fires (on update to selcode), the status field has already beenchanged. So my trigger to record the changes from inserted and deleted donot get the true 'before' value of the status field.The app does use a log table that tracks these changes. The problem I amhaving is that 2 records are created, one for the change to selcode andanother for the change to status.I am looking for help with a script to combine the existence of these 2 logrecords into 1 unique record or occurance that I can track.example:ordlog: table that logs order changesordernr: order numbervarname: name of field being changedold_value: contents of field before changenew_value: contents of field after changesyscreated: date/time of log entrySELECT ordernr, varname, old_value, new_value, syscreatedFROM ordlogwhere varname = 'selcode' and ordernr = '10580'SELECT ordernr, varname, old_value, new_value, syscreatedFROM ordlogwhere varname = 'status' and ordernr = '10580' and old_value = 'A' andnew_value = 'O'So I need a way to combine these 2 log entries into a unique occurance. Theordernr and syscreated could be used to link records. syscreated alwaysappears to be the same for the 2 log entries down to the second. Selcodecan change from NULL to a number of different values or back to NULL.Statusis either 'A' for approved or 'O' for open. An order can have many logentries during its life. The selcode may be changed several times for thesame order.Ideally, I would like a result that links 2 log entries and shows the statuschanged from 'A' to 'O' when selcode changed.Thanks for your time.

View 1 Replies View Related

SQL Statement To Return First Unique Record

Jan 19, 2007

I've been searching and trying out SQL statements for hours and I'mstill having a problem.I'm querying 3 tables... and I only want the first unique recordreturned.Currently, the data returned looks like this..............New York New York ANew York New York BNew York New York CLos Angeles California ALos Angeles California BLos Angeles California CI want the select statement to return this instead...New York New York ALos Angeles California AI'm using MS SQL server.please help?thanks for your help.

View 4 Replies View Related

Unable To Show 0 To Many Records With Inner Join

May 2, 2008

I am having problem  with Inner joining of tables
 
my query is..
 Select j.jobSubject,e.eOrganization ,jv.JobClick,j.jobID from dbo.tbl_Jobs jinner join  dbo.tbl_Employer e on e.mId=j.jobCreatedByIDinner join dbo.tbl_JobView jv on jv.JobID=j.jobID
order by jv.JobClick desc This query returns 1 to many records
 
But I need the query should return  0 to many record . .yes I have already know inner join does not handle my problem so plz suggest me which type of join would solve my problem
 

View 3 Replies View Related

How To Join And Show Data In Browser

Mar 21, 2007

This is the select statement I'm currently using but I can't seem to get the browser to show any data. It just shows the table structure.

I use the g and the p as aliases. Easier maintenance this way.

strSQL = "SELECT g.GuestID, g.ProgramID, p.ProgramID AS Expr1, g.GuestName, g.GuestDescription, p.URL, p.Description FROM dbo.T_ProgramGuests g INNER JOIN dbo.T_ProgramLinks p ON g.GuestID = p.LinkID WHERE p.ProgramID = " & Request("ProgramID")

I have an ASP page where the above sql code is embedded. I have two SQL tables. One is called T_ProgramGuests and the other is called T_ProgramLinks. The asp page basically does a read only of the two tables and is suppose to return the results inside of the html tables I have in the asp page. But all I see when I test is the html and the tables are devoid of data.

HERE IS THE PAGE CODE:
<%
on error resume next
set con = Server.CreateObject("ADODB.Connection")
con.Open "File Name=E:webserviceCompanyCompany.UDL"
set recProgram = Server.CreateObject("ADODB.Recordset")

strSQL = "SELECT g.GuestID, g.ProgramID, p.ProgramID AS Expr1, g.GuestName, g.GuestDescription, p.URL, p.Description FROM dbo.T_ProgramGuests g INNER JOIN dbo.T_ProgramLinks p ON g.GuestID = p.LinkID WHERE p.ProgramID = " & Request("ProgramID")

recProgram.Open strSQL,con

%>

<TABLE border="1" cellspacing="0" border="1" width="70%">

<p><b>Guest Name and Description:</b></p>
<tr>
<th width="35%" align="left">Guest Name</th>
<th width="45%" align="left">Guest Description</th>
<tr>
<TD headers="t2"><%=recProgram.Fields("GuestName")%></TD>
<TD headers="t3"><%=recProgram.Fields("GuestDescription")%></TD>
</tr>
</table>

<TABLE border="1" cellspacing="0" border="1" width="70%">
<br /><br />
<p><b>URL and Description:</b></p>
<tr>
<th width="35%" align="left">URL</th>
<th width="45%" align="left">Description</th>
<tr>
<TD headers="t4"><%=recProgram.Fields("URL")%></TD>
<TD headers="t5"><%=recProgram.Fields("Description")%></TD>
<%'
recProgram.Close
con.Close
set recProgram = nothing
set con = nothing
'response.write err.Description
%>

</body>
</html>


I am new to using the advanced features of SQL and could sure use some help with this.

View 2 Replies View Related

Trying To Identify A Unique Record On Two Separate Tables

Oct 31, 2007

Hello,
I am working with a database that among other things uses multipart keys as the unique indexes which are not consistent from say one table where a parent record resides to another table which contains related child records. For example I am working with two tables right now, one that contains content that I'll call Contents and the other which contains Usage information about the contents (number of view, a rating and comments give by a customer) which I'll call ContentsUsage. The system that manages the data for the tables has a versioning system by which, whn a content item is added (first time) a "unique" id (guid) and a version number of 1 is created along with the rest of data items in the Contents table and likewise in the ContentsUsage table (essentially a one to one mapping) on the like named fields in that table. Now, each time a given record in the Contents table is updated a new version, with the same guid is created in the Contents and ContentsUsage table. So one side I have:ContentGUID > AAAAVersion > 1ContentGUID > AAAAVersion > 2And the other table (ContentsUsage)ContentGUID > AAAAVersion > 1ContentGUID > AAAAVersion > 2
While both of these tables have a quasi-unique record (row_id) of type char and stored as a guid neither obviously are the same in the two tables and having reviewed the database columns for these tables I find that the official unique key's for these tables are different (table 1, Contents combines the ContentGUID and Version) as the composite / mutli-key index, while table ContentsUsage uses the RowGUID as it's unique index. 
Contents                                   RowGUID (unique key)ContentGUIDVersionViewsRatingComments................RowGUID ContentGUID (unique key)Version (unique key)Description.....
Bearing this in mind I am unable of course to link directly the two tables by using the just the ContentGUID and have to combine the additional Version to I believe obtain the actual "unique" record in question. The question is in terms of writing queries, what would the most efficient query be? What would be the best way to join the two in a query? And are there any pitfalls with the current design that you can see with the way this database (or specifically these tables are defined)? It's something I inherited, so fire away at will on the critique. Having my druthers I would have designed these tables using a unique key of type int that was autogenerated by the database.
Any advice, thoughts or comments would be helpful.
Thanks,P. 
 
 
 
 

View 8 Replies View Related

Table Relationship Question For Unique Record

Apr 9, 2008

Hello Hello,
This Noob has a question.
I have been atempting for days to figure this out.
I have this set up: (See Below)

The Problem I am having is occuring at the Table named OU in Maroon below.
It combines 2 chains of keys into one table to try and make a unique record.
The problem is that it is not.

Pasted below is a Query run on the data within the tables:
As you can see certain data is getting duplicated in this tabel.
I want 1 Unique record in the OU table based upon the Study ID Primary Key and the zCombined Primary Key.

Any Ideas as to what is wrong, or how to make it work would defineatly be appreciated.

Thanks a Bunch


Table: Sponsor
PK: Sponsor ID

Table: Protocol
PK: ProtocolID
FK: Sponsor ID

Table: Study
PK: StudyID
FK: ProtocolID
Table: OUPK: OUIDFK: StudyIDFK: zCombinedID

Table:zCombined
PK: zCombinedID
FK: TempID ~ To Temp Table
FK: ShipTypeID ~ To Ship Type Table
FK: CoordinatorID ~ To Coordinator Table
FK: BoxTypeID ~ To Box Type Table







Sponsor

Protocol

Study

OU~Column1

OU~Column2

Box

Coordinator

Ship Type

Temp


Omni

AAAAA

XPG

S0101

NA

Wheaton

Raul Vargas

Daily

-70


Omni

AAAAA

XPG

S0101

NA

Matrix

Raul Vargas

Daily

-70


Omni

AAAAA

XPG

S0101

NA

B-1

Raul Vargas

Daily

-70


Omni

AAAAA

XPG

S0101

NA

9 x 9 4mL

Raul Vargas

Daily

-70


Omni

AAAAA

XPG

S0101

NA

9 x 9 2mL

Raul Vargas

Daily

-70


Omni

AAAAA

XPG

S0101

S0201

Wheaton

Mike Keane

DNA

-40


Omni

AAAAA

XPG

S0101

S0201

Matrix

Mike Keane

DNA

-40


Omni

AAAAA

XPG

S0101

S0201

B-1

Mike Keane

DNA

-40


Omni

AAAAA

XPG

S0101

S0201

9 x 9 4mL

Mike Keane

DNA

-40


Omni

AAAAA

XPG

S0101

S0201

9 x 9 2mL

Mike Keane

DNA

-40

View 3 Replies View Related

To Get An Unique Sequence Number (record Locking)

Aug 27, 2007

can someone pls show me a way to get an unique sequence at below senario:

PC1 & PC2 using their own local client progam to access to Database Server at SERVER1.
In the SERVER1, there is a table SEQUENCE in a database DATABASE1.
And the table's structure of SEQUENCE are SeqType & SeqNo.
Here is the sample data:

SeqType SeqNo
Invoice 100
DeliveryOrder 200

Now, how to prevent PC1 & PC2 to get a same Invoice No. if they request the Invoice No. at the same time?
Is it possible to lock the record Invoice when i perform a SELECT statement, then i update the Invoice to 101, lastly release the lock for Invoice?

pls advise. thanks.

View 1 Replies View Related

How To Control One Unique Record Per Proc Instance??

Oct 19, 2007

Greetings,

I am running a proc (PROC1) that gets one record at a time and does some work against it.



select min(myid) as NextID
from tbl_ListOfThingsToDo
where AlreadyDone is null

Then once I have the MyID, I set the 'AlreadyDone' bit to True so that no one else picks that record up.


update tbl_listofThingsToDo set AlreadyDone=1 where MyID=(from above)


If there is only one PROC1 running, this is no problem. He just keeps grabbing the next record to operate on.

--but--

If I kick off multiple instances of PROC1 for scaleability reasons, how can I make sure that only one instance gets the next record? For example, couldn't the second instance get the same myid BEFORE the first instance has written that he already got it?

Design is to run 3-5 instances of this to get extra cycles.

Let me know your thoughts, and thanks..


Dan Ribar


View 3 Replies View Related

Selecting Unique Rows In A Join

Mar 20, 2008

I got the following query:SELECT TOP (8) ext.extID, ext.Quote, ext.sourceTitle, ext.extRating, gf_game.gameID, gf_game.catID, gf_game.URL, gf_game.TitleFROM         gf_game_ext AS ext INNER JOIN                      gf_game ON gf_game.gameID = ext.gameIDWHERE     (ext.Approved = 1)ORDER BY ext.extID DESC which is e.g. producing this output: 6000 -some text- Title 90 1960 2 tom-cl tom cl5999 -some text- title 90 1960 2 tom-clcl asdf5998 -some text- title 90 1959 2 tom-cl-cl asdfWhat I'd like to do now is to filter out the duplicate GameIDs (= 1960) so that just one unique row with the gameid 1960 is remaining. If I put in a SELECT DINSTINCT TOP(8) it just counts for the table ext, but I need it to count for gf_game.gameID - is that possible?Thanks a lot! 

View 9 Replies View Related

Help With A Join That Needs To Return Unique Records

Apr 28, 2008

Hi All,

I need a bit of help with a join. I have 2 tables :

TradeSummary
has fields : SymbolID, CurrentPrice, TotalValue

Trades
has fields : SymbolID, TradeID, ExecutionTime, TradeValue

TradeSummary has one entry for each SymbolID, while Trades contains one or more entries per SymbolID


and what I want to retreive is :


For every item in TradeSummary get CurrentPrice, TotalValue from TradeSummary
and also get TradeValue from Trades for the record for max(ExecutionTime)
tables are joined on TradeSummary.SymbolID = Trades.SymbolID

Every attempt of mine so far returns multiple rows for each SymbolID - I want only one row per SymbolID

thanks in advance

View 11 Replies View Related

Help With A Join To Return Unique Values

Apr 28, 2008

Hi All,

I need a bit of help with a join. I have 2 tables :

TradeSummary
has fields : SymbolID, CurrentPrice, TotalValue

Trades
has fields : SymbolID, TradeID, ExecutionTime, TradeValue

TradeSummary has one entry for each SymbolID, while Trades contains one or more entries per SymbolID


and what I want to retreive is :


For every item in TradeSummary get CurrentPrice, TotalValue from TradeSummary
and also get TradeValue from Trades for the record for max(ExecutionTime)
tables are joined on TradeSummary.SymbolID = Trades.SymbolID

Every attempt of mine so far returns multiple rows for each SymbolID - I want only one row per SymbolID

thanks in advance

View 7 Replies View Related

A Recordset Obtained Via ADO Doesn&#39;t Show The First Record Using Data Report

May 30, 2001

Te first record of a Recordest obtained from a Command Object executing a Stored Procedure, doesn't show the first record when I asociate this to a data report.(VB6 - SQL7) (ADO 2.1)

If I execute the stored procedure directly from query analizer, I have obtained the right resultset.

Does anyone Knows what could be happening?

Thank You ...

View 1 Replies View Related

SQL Server 2012 :: Selecting Unique Record From A Table

Feb 10, 2014

I have a table (Billing Table) having multiple records for people having one record per person per each month.

How to get a list of the guys having record just for one month (say feb) and doesn't have any other months.

View 4 Replies View Related

How To Fetch Record From Temp Table - Unique Combination

Sep 23, 2014

Table :StudentTeacherRelation

Id StdId TeacherName Day subject
1 1 Archana Monday English
2 1 Archana Tue Marathi
3 1 Shama Wed Hindi
4 1 shama Thus Hindi
5 1 Kavita Fri Hindi
6 2 Archana Mon english
7 2 Dipti Tues Hindi

Second table : Student

Id Sname Cid
1 Shalini 1
2 Monika 1
3 Rohan 3

I want to fetch uniq combination of stuid and subject.Result should show all subject of student whether may be teachername and day. If I choose shalini whose stuid is 1,all subject for shalini(hindi,english,marathi) should come. Record from either of three should come

Id StdId TeacherName Day subject
3 1 Shama Wed Hindi
4 1 shama Thus Hindi
5 1 Kavita Fri Hindi

I want fetch studentname along with teachername,day and subject whose cid = 1 here is my query

select Student.Sname,TeacherName, Day,subject
from StudentTeacherRelation
inner join Student
Student.id = StudentTeacherRelation.StuId
where cid = 1

I want place result of it in temp,Want fetch max(id) from temp table by doing group by on Sname and Subject.find all id from temp table where that id present in max id.

show
Id StdId TeacherName Day subject
where (1,2,3,4,5,6,7-- all id from temp) in (1,2,5,6,7 -- max id from temp by doing group by on Sname and subject)

So it will show record Id StdId TeacherName Day subject where id is 1,2,5,6,7.Only five record should come.How to do that?

View 1 Replies View Related

SQL Server 2012 :: Finding Duplicates And Show Original / Duplicate Record

Nov 3, 2014

There are many duplicate records on my data table because users constantly register under two accounts. I have a query that identify the records that have a duplicate, but it only shows one of the two records, and I need to show the two records so that I can reconcile the differences.The query is taken from a post on stack overflow. It gives me 196, but I need to see the 392 records.

How to identify the duplicates and show the tow records without having to hard code any values, so I can use the query in a report, and anytime there are new duplicates, the report shows them.

SELECT
[groom_first_name]
,[groom_last_name]
,[bride_first_name]
,[bride_last_name]

[code]....

View 5 Replies View Related

T-SQL (SS2K8) :: Identify Columns Which Will Create Unique Record In A Table

Sep 15, 2014

I am looking to create a script that will go through a table a pick out the necessary columns to create a unique record. Some of the tables that I am working with have 200 plus columns and I am not sure if I would have to list every column name in the script or if they could be dynamically referenced. I am working with a SQL server that has little next to no documentation and everytime I type to mere some tables, I get too many rows back.

View 4 Replies View Related

T-SQL (SS2K8) :: How To Show Multiple Values In Column Of Join Query

Nov 6, 2014

in my table i ve the column of item code which contains '1000' ,'2000' ,'3000' series i jus wanna display the output of item codes '1000','2000'series and some of ('3000019','3000020','3000077','3000078').

i tried in my join query

these code left(itemcode,4) in ('1000','2000') or itemcode in ('3000019','3000020','3000077','3000078')

its taking so much of time how t o solve ?

View 1 Replies View Related

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

T-SQL (SS2K8) :: Convert Unique Identifier From String To Use In A Join / Where Clause

Jan 6, 2015

I am wanting to get the job name based on sys.sysProcesses.[Program_name] column. Why is this query not returning any results even though the 2nd substringed guids are found the the sysJobs table?

SELECTCASE
WHEN RTRIM([program_name]) LIKE 'SQLAgent - TSQL JobStep (Job %' THEN J.Name
ELSE RTRIM([program_name])
END ProgramName
, Val1.UqID
, Val1.UqIDStr

[Code] ......

View 6 Replies View Related

PC SQL Server Table (with A Column Classified Unique) Synchronizes (using Merge) With 2 PPCs SQL Mobile Adding The Same Record

Aug 29, 2006

Hi, I have a doubt about the behaviour of SQL Server 2005 in the situation I'm going to describe you.
Suppose that you have a SQL Server 2005 database on your PC, and suppose that this database has a table with a column classified as "unique" (so it's impossible for this table to contain 2 records having the same value in this column).
Suppose that you publish this database and you create 2 SQL Server Mobile 2005 subscriptions on 2 Pocket PCs.
Suppose now that the first PPC (using an embedded program) creates a record with a certain value for the column (and adds it to the table), and the second PPC makes the same thing (it inserts a record with the same column value of the first PPC).
At this point, you connect the 2 PPCs to your PC (one by one, of course), to synchronize (using merge replication) the databases...

WHAT HAPPENS??? Does an error raise?
Must you give a publication setting in which you say that, if this situation occurs, PC SQL Server holds the last (or the first, as you decide) record acquired? Is it possible?

Thank you very much

View 1 Replies View Related

Selecting The First Record In A Join?

Mar 1, 2012

I have one table like this:

Code:
CREATE TABLE DlIndexTable
(SessionStartTime DATETIME NOT NULL PRIMARY KEY, SchemaID INTEGER NOT NULL,
DLBaseRate REAL NOT NULL)

and one like so:

Code:
CREATE TABLE DlTextDataTable (
SessionStartTime DATETIME NOT NULL REFERENCES DlIndexTable,
ChTimestamp FLOAT NOT NULL, Channel01data VARCHAR (255),
Channel02data VARCHAR (255), ... , Channel16data VARCHAR (255),
CONSTRAINT TxtDatPriKey PRIMARY KEY (SessionStartTime, ChTimestamp))

I want to get some combined data from both tables, so right now I am joining them at the SessionStartTime column, which is a primary key in the first and a foreign key in the second table, something like this:

Code:
SELECT DlIndexTable.SessionStartTime, DlTextDataTable.Channel01data
FROM DlIndexTable
LEFT JOIN DlTextDataTable
ON DlIndexTable.SessionStartTime = DlTextDataTable.SessionStartTime
WHERE DlIndexTable.SessionStartTime BETWEEN '2006-10-13 16:40:08.790' AND '2012-03-01 17:54:30.930'
ORDER BY DlIndexTable.SessionStartTime, DlTextDataTable.ChTimestamp

The trouble is that this query, exactly as requested, gives me all the entries from the second table matching the first, while I really would like to pick just one row (preferably, the first chronologically - by ChTimestamp) so that the first column (SessionStartTime) has distinct entries in the resulting table. What would be the simplest way of doing that? Performance is not a big priority over simplicity since the first table could have only a few hundred rows (maybe a couple of thousand), while the second will be real tiny.

View 10 Replies View Related

Left Outer Join And Last Record

Sep 21, 2007

my table isCustomer Customer Id--------- ----------------Mary 1Jhon 2Anna 3OrderId CustomerId Product ProductDesc------- --------- --------- -----------1 1 video bla bla2 1 tv bla bala3 2 video bla bla4 2 cd bla blaI want to see-------marry tv bla blaJohn cd bla blaanna

View 3 Replies View Related

Multiple Record Delete Via Join

Feb 25, 2008

Hi,

I have a table with a large number of records that I need to delete, before attempt to perform the delete I also archived the records to another table.

So I need to delete all of these selected records stored in the archive table from the main table. I can now reference all the records that qualify for the delete in the main table by performing a join on the archive table like so:

select * from my_main_table a
join my_archive_table b
on a.distinct_id=b.distinct_id
and a.surrogate_key=b.surrogate_key
and a.identifier=b.indentifier

So all the records check out to be the ones I'd like to perform a delete on but I just can't figure out how to perform a delete of the records with little or no change to the existing query.

Obviously something like this won't work:

delete from my_main_table a
join my_archive_table b
on a.distinct_id=b.distinct_id
and a.surrogate_key=b.surrogate_key
and a.identifier=b.indentifier

Though it would be nice if it did.:D

So my question is how would I use the existing query with some modification to delete only the records that this query returns. I've tried selection of records in the main table based on the existing records in the archive table but it can return a higher number of records than what I know is expected. I actually need the join specified to be in place to do it.

Can anyone render any assistance on this one???

I would certainly appreciate it.

Thanks.

View 1 Replies View Related







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