Join 3 Tables Getting Rows Repeating

Jan 27, 2014

I am using three tables/view.

The first is a vendor table where I am pulling company/ID/name

I am using a left join to the other two tables on company/ID

The problem I am having is if the second table has 8 rows and the third table just has 1 row it will repeat 8 times.

How do I show all 8 from the second table but only the 1 from the third table?

You can see below that the voucher number and amount repeat

vendor_idvendor_namepo_nopo_amountvoucher_no amount_due
36999VITEK6012838 $174.00 2622666 $(1,791.00)
36999VITEK6016464 $822.90 2622666 $(1,791.00)
36999VITEK6017791 $876.00 2622666 $(1,791.00)
36999VITEK6025495 $600.00 2622666 $(1,791.00)
36999VITEK6029781 $930.00 2622666 $(1,791.00)
36999VITEK6034433 $3,264.00 2622666 $(1,791.00)
36999VITEK6037821 $2,715.00 2622666 $(1,791.00)

View 1 Replies


ADVERTISEMENT

Transact SQL :: Join Two Tables With Multiple Rows?

Aug 13, 2015

I have to join two tables and i need to fetch All records from @tab2 and only max date record from @tab1 that ID is present in Tab2

1.) @Tab1 have multiple records for each ID

2.) @Tab2 also have multiple records for each ID

3.) Kind of Lef Outer join those tables with ID and take all records from @tab2 and only Max of date from @tab1 and order by ID and Date

Note: @Tab1 always have lesser dates than @tab2 for each ID

Tables looks like as follows 

declare @tab1 table (id varchar(3), effDt Date, rate int)
insert into @tab1 values ('101','2013-12-01',5)
insert into @tab1 values ('101','2013-12-02',2)
insert into @tab1 values ('101','2013-12-03',52)

[code]....

In the given ex, ID 103 should not come as it is not present in @tab2, ID 104 should come even it is not present in @tab1 as we ahve to use left outer join Result should like follows.

View 3 Replies View Related

Selecting Rows From Two Tables With JOIN And Ordering Problem

Dec 8, 2007



Hi,

First the environment: two tables A and B.

Table A: ID (unique-identifier)
Table B: ID_A (unique-identifier to A.ID, relation)

DTime (datetime)

Rows (id1 and id2 are Id examples):
A: id1
id2
B: id1 and 12:00:00 (date not important)
id1 and 13:00:00
id2 and 12:00:00

Example:
SELECT A.ID, B.DTIME
FROM A
LEFT JOIN B ON B.ID_A = A.ID
WHERE B.DTime < '14:00:00'
ORDER BY NEWID()

When I run this, I get the three rows of table B. But what I want is to get each table A row once, and get the nearest datetime of WHERE expression from the relation of table B.
So, the result must been two rows, id1 and id2, and id1 with '13:00:00' row because this is the nearest value of '14:00:00'.

How can I do this? DISTINCT trying by A.ID of SELECT, but doesn't work. Also ORDER BY B.DTime will work, but not random by NEWID() anymore.

Thank you.

View 3 Replies View Related

Rows Repeating

Jun 4, 2008

This is actually not asp.net, but I'm hoping someone can help me. I have a report that is pulling from a couple of different tables. I am trying to add a meal choice to the report. Let's say they have the option of choosing chicken, beef or fish. They check the checkbox next to the choice. My report is pulling the infor, but it is putting 3 rows for each person not taking into consideration what choice they chose. The checkbox's all write to the same column - ses. Here is the code for the stored procedure:
 CREATE PROCEDURE [dbo].[spGetCourseEmailList1]( @Code1 char(9)) AS SELECT DISTINCT  dbo.[names].lname as LastName,  dbo.[names].fname as FirstName,dbo.[evser].ses as MealChoice,dbo.[evldg].paid as AmountPaid, dbo.[names].gp as PreferredAddress,  dbo.[names].mi as MiddleInitial,  dbo.[names].nname as NickName,  dbo.[names].xname as Suffix,  dbo.[names].hphone as HomePhone,  dbo.[names].email as EmailAddress,  dbo.[names].addr1 as HomeAddress1,  dbo.[names].addr2 as HomeAddress2,  dbo.[names].city as City,  dbo.[names].st as State,  dbo.[names].zip as ZipCode,  dbo.[firms].fname1 as FirmName1,  dbo.[firms].fname2 as FirmName2,  dbo.[firms].faddr1 as FirmAddress1,  dbo.[firms].faddr2 as FirmAddress2,  dbo.[firms].fcity as FirmCity,  dbo.[firms].fst as FirmState,  dbo.[firms].fzip as FirmZip,  dbo.[firms].fphone as FirmPhone,  dbo.[names].udflist1 FROM dbo.[firms] INNER JOIN dbo.[names] ON dbo.[firms].firm = dbo.[names].firm
INNER JOIN dbo.evldgON dbo.[names].id = dbo.[evldg].id
INNER JOIN  dbo.evregON dbo.[evldg].id = dbo.[evreg].id
Full OUTER  JOIN dbo.evserON dbo.[evreg].code1 = dbo.[evser].code1
WHERE dbo.[evldg].code1 = @Code1 AND  dbo.[evreg].code1 = @Code1 AND dbo.[evser].code1 = @Code1 AND dbo.[names].xwebflag <> 'Y'ORDER BY dbo.[names].lname, dbo.[names].fnameGO
The items in bold are what I added.
 

View 3 Replies View Related

Nested Join To Return Only Rows With Null Values From All Tables

Oct 17, 2007



Hello,

I have this INNER JOIN that is fine to show all possible combinations. But I need to show only rows that have one or more Null values in tbIntersect.

Should I use nested LEFT JOINT? How?

This is the SQL statement:
sSQL = "SELECT DISTINCT tbCar100.Car100_ID, tbCar100.Description100 AS [Caractéristique 100], " & _
"tbCar200.Car200_ID, tbCar200.Description200 AS [Caractéristique 200], " & _
"tbCar300.Car300_ID, tbCar300.Description300 AS [Caractéristique 300], " & _
"tbCar400.Car400_ID, tbCar400.Description400 AS [Caractéristique 400], " & _
"tbCar500.Car500_ID, tbCar500.Description500 AS [Caractéristique 500], " & _
"tbCar600.Car600_ID, tbCar600.Description600 AS [Caractéristique 600], " & _
"tbCar700.Car700_ID, tbCar700.Description700 AS [Caractéristique 700], " & _
"tbProducts.Prod_ID, tbProducts.PartNumber AS [Part Number] , tbProducts.Description AS [Description] , tbProducts.DateAdded AS [Date] " & _
"FROM tbProducts INNER JOIN (tbCar700 INNER JOIN (tbCar600 INNER JOIN (tbCar500 INNER JOIN (tbCar400 INNER JOIN (tbCar300 INNER JOIN (tbCar100 INNER JOIN " & _
"(tbCar200 INNER JOIN tbIntersect ON tbCar200.Car200_ID = tbIntersect.Car200_ID) " & _
"ON tbCar100.Car100_ID = tbIntersect.Car100_ID) ON tbCar300.Car300_ID = tbIntersect.Car300_ID) ON tbCar400.Car400_ID = tbIntersect.Car400_ID) ON tbCar500.Car500_ID = tbIntersect.Car500_ID) ON tbCar600.Car600_ID = tbIntersect.Car600_ID) ON tbCar700.Car700_ID = tbIntersect.Car700_ID) ON tbProducts.Prod_ID = tbIntersect.Prod_ID " & _
";"


Here is the content of the tbIntersect table:
Car100_ID Car200_ID Car300_ID Car400_ID Car500_ID Car600_ID Car700_ID Prod_ID ID
1 1 1 1 1 1 1 1 1
1 2 1 1 1 1 1 19
1 3 1 1 1 1 1 20


I need to return the rows that have null data, ex: second row because Prod_ID is NULL and third row because Car300_ID is NULL. In fact I need the data from the other joint tables that correspond to these ID fields.

Thanks

View 5 Replies View Related

SQL Query Repeating Rows.

Dec 12, 2007

i have a query when i run it shows data rows repeating like 5 times. I am not sure what am i doing wrong. hope someone can help me out.
 this is my query.
SELECT "INVOICEDETAILS"."SeviceAmount", "RptSalesUser"."SalesPersonId", "RptSalesUser"."SalesPersonName", "RptSalesUser"."TemplateStatus", "INVOICE"."InvoiceDate"
FROM   ("imacstest"."dbo"."INVOICE" "INVOICE" INNER JOIN "imacstest"."dbo"."INVOICEDETAILS" "INVOICEDETAILS" ON "INVOICE"."InvoiceNo"="INVOICEDETAILS"."InvoiceNumber") INNER JOIN "imacstest"."dbo"."RptSalesUser" "RptSalesUser" ON ("INVOICE"."InvoiceNo"="RptSalesUser"."invoiceNumber") AND ("INVOICEDETAILS"."InvoiceNumber"="RptSalesUser"."invoiceNumber")
WHERE  "RptSalesUser"."TemplateStatus"='A' AND ("INVOICE"."InvoiceDate">={ts '2007-01-01 00:00:00'} AND "INVOICE"."InvoiceDate"<{ts '2007-12-13 00:00:00'}) AND "RptSalesUser"."SalesPersonId"=5 and "Invoice"."InvoiceNo"='1004447' ORDER BY "RptSalesUser"."SalesPersonId","Invoice"."InvoiceDate"
when i execute this i get about 12 data rows which are fine but then the same 12 data lines repeats 4 more times. hope someone be able to help me quick.
 

View 17 Replies View Related

Remove Repeating Rows

Apr 29, 2004

I would like to know how to produce the following in a query.

Parent Child
---------------
Dave Sarah
.......... Brad
.......... Alice
.......... Hanna

Rather than:

Parent Child
---------------
Dave Sarah
Dave Brad
Dave Alice
Dave Hanna

View 5 Replies View Related

Remove Rows Repeating More Than Twice

Nov 29, 2007

Ok, so I've been racking my brains on this one for a while now and figured it was time to ask for some help...

I have a table named tblAppInfo that looks something like this:



Code Block
user_name app_name app_ver

User1 MS Word 2000
User2 MS Word 2000
User3 MS Excel 2000
User4 MS Excel 2000
User5 MS Excel 2000
User6 MS Excel 2000
User7 MS Outlook 2000
User8 MS PowerPoint 2000
User9 Adobe Acrobat 5.0
User10 Adobe Acrobat 6.0
User11 Adobe Acrobat 7.0





What I want to do is remove any rows that repeat the app_name and app_ver more than twice. Basically in the example above, it would remove the lines that have MS Excel 2000 (as it's listed 4 times). MS Word 2000 would stay as it's only listed twice. As would Outlook and PowerPoint. All 3 Adobe's would also stay as their versions are different.

I've tried the following but it still repeats applications that occur more than twice:




Code BlockSELECT user_name, app_name, app_ver
FROM tblAppInfo
GROUP BY app_name, app_ver, user_name
having count(distinct app_name + app_ver + tblAppInfo.host_name) < 3
ORDER BY app_name, app_ver





I've also tried using nested select statements and everything else in my arsenal to no avail. I hope someone here will be able to help me out as I'm afraid I'll go bald if I try anymore!

Thanks in advance!

Tom

View 6 Replies View Related

Convert Repeating Blocks Of Columns Into Rows?

Feb 17, 2015

writing SQL code to convert blocks of columns into rows.

Example,

Id A1 A2 B1 B2
1 1 1 1 1
2 2 2 2 2
3 3 3 3 3

into

Id Group Value
1 A 1
1 A 1
1 B 1
1 B 1
2 A 2
2 A 2
2 B 2
2 B 2

View 2 Replies View Related

Combine 2 Rows From Derived Table Into 1 Row W/o Repeating Query?

Aug 1, 2007

I'm trying not to use a temp table, but i may have to do so..
I'm using sql2005 for this case.

i have a derived table that makes the following results:



ID Status Name

2 1 "A"

2 2 "B"



I want to get the following:

ID Name1 Name2

2 "A" "B"



but like I said before, I can't repeat the query that gets the first 2 rows, as it's pretty invovled. a temp table is the best route I see right now, but I just wanted to be sure I'm not missing something. If I've aliased it as 'results', is there a way to alias results again as something else? or maybe a trick with CTEs? I will try that! It seems promising.

View 1 Replies View Related

Converting Repeating Fields In Single Row To Multiple Rows

Sep 4, 2007

Hi there

I have loaded a csv file into a table. Some fields within the file contain a varying number (up to 10) of subfields seperated by line feed characters.

It looks sort of like this

Customer No. Payments Dates
111 pay1|pay2|pay3 dat1|dat2|dat3

I created an Unpivot transformation, and I got

Customer No. Description Detail
111 Payments pay1|pay2|pay3
111 Dates dat1|dat2|dat3

After a Derived Column transformation I got

Customer No. Description Line1 Line2 Line3
111 Payments pay1 pay2 pay3
111 Dates dat1 dat2 dat3

But what I really want is to end up with this:

Customer No. Payments Dates
111 pay1 dat1
111 pay2 dat2
111 pay3 dat3

Is there a transformation that will get me there, or do I just need some cunning SQL?

I tried to Pivot my way back to happiness but I couldn't get it to work

View 4 Replies View Related

Combine 2 Rows From Derived Table Into 1 Row W/o Repeating Query?

Aug 1, 2007



I'm trying not to use a temp table, but i may have to do so..

i have a derived table that makes the following results:

ID Status Name
2 1 "A"
2 2 "B"

I want to get the following:
ID Name1 Name2
2 "A" "B"

but like I said before, I can't repeat the query that gets the first 2 rows, as it's pretty invovled. a temp table is the best route I see right now, but I just wanted to be sure I'm not missing something.

View 5 Replies View Related

How To Join 3 Tables Using Left Or Right Join Keyword?

Aug 17, 2007

Hi guys,

I'll appreciate any help with the following problem:

I need to retrieve data from 3 tables. 2 master tables and 1 transaction table.

1. Master table TBLOC contain 2 records :
rcd 1. S01
rcd 2. S02

2. Master table TBCODE contain 5 records:

rcd 1. C1
rcd 2. C2
rcd 3. C3
rcd 4. C4
rcd 5. C5

3. Transaction table TBITEM contain 4 records which link to 2 master table:
rcd 1. S01, C1, CAR

rcd 2. S01, C4, TOY
rcd 3. S01, C5, KEY
rcd 4. S02, C2, CAR



I use Left Join & Right Join to retrieve result below (using non-ASNI method) but it doesn't work.

Right Join method:


SELECT C.LOC, B.CODE, A.ITEM FROM TBITEM A RIGHT JOIN TBCODE B ON A.CODE = B.CODE

RIGHT JOIN TBLOC C ON A.LOC = C.LOC

GROUP BY C.LOC, B.CODE, A.ITEM ORDER BY C.LOC, B.CODE



When I use Non-ASNI method it work:



SELECT C.LOC, B.CODE, A.ITEM FROM TBITEM A, TBCODE B, TBLOC C

WHERE A.CODE =* B.CODE AND A.LOC =* C.LOC

GROUP BY C.LOC, B.CODE, A.ITEM ORDER BY C.LOC, B.CODE

Result:

LOC CODE ITEM
-----------------------------
S01 C1 NULL
S01 C2 NULL
S01 C3 CAR
S01 C4 TOY
S01 C5 KEY
S02 C1 NULL
S02 C2 CAR
S02 C3 NULL
S02 C4 NULL
S02 C5 NULL


Please Help.

Thanks.






View 3 Replies View Related

Self Join To Find Rows With Same Value In A Col

May 14, 1999

Hi,

I forgot the syntax to to a self-join to find all rows that have
duplicate values. Could someone post the answer to the following example:

Column1
-----
x
y
z
x

After the select statment runs "x" would be the output.

Thanks,
Ken

View 2 Replies View Related

Deleting Rows Using A Join

Aug 27, 2001

I have two tables. Table 1 contains a distinct ID(3,4,5). Table 2 contains multiple ID's(3,3,3,3,3,4,4,4,5,5,5). I want to be able to use a join. If an ID is found in table 2, remove all entries of it. Any ideas? Thanks...

delete b.id
from table1 a join table2 b on a.id = b.id

View 1 Replies View Related

Need Help - SQL Query To Join Two Rows

May 22, 2008

Current ResultSet
------------------
ColA ColB
TEST1 111
TEST1 222
TEST2 333
TEST3 444
TEST3 555

I am currently outer-joiing two tables to retrive some data in the above format. My intent is to modify the query so I can retrive the data in below fashion.

Intended ResultSet
------------------
ColA ColB
TEST1 111,222
TEST2 333
TEST3 444,555

Can someone please assist with this? I am not sure if it is possible in a direct query or not... Any expert advice is appreciated.

View 1 Replies View Related

Count Rows With Join

Jun 21, 2014

This is my sql string. It counts all the rows in Questions table but it should only count the rows where id in Quizzes matches the quiz column in Questions table.

"select Quizzes.name, Quizzes.id, count(Questions.quiz) as total from Quizzes inner join Questions on Quizzes.id=Questions.quiz"

Why isnt it doing what I want it to do?

View 4 Replies View Related

Need All Rows:Outer Join + WHERE

Jul 29, 2007

Hi, I would appreciate help on the following query I got stuck with;

I've got 2 tables "AccountList" and "PeriodBalance";
I need to return all the accounts form "AccountList" and their balance form "PeriodBalance";
The user will select a period for which the balances should be returned, if there is no balance for the period... 0 should be returned. "PeriodBalance" would not have an entry if there is no balance for the period.

There is only 3 possible periods (1, 2 or 3)
And there is only one balance per period per account;

TABEL 1: AccountList:
AccNo
100
200
300

TABLE 2: PeriodBalance:
AccNo PerID PerBal
100 1 1000
100 2 1750
100 3 1800
300 1 3200
300 3 3500

This is what is what I need returned by the query, assuming we are selecting PerID 2: (WHERE PerID=2)
AccNo PerID PerBal
100 2 1750
200 2 0
300 2 0

I've included ISNULL(PerID,4) = 4 in my WHERE clause...this worked for returning AccNo 200.
My problem is AccNo 300 in not NULL....it has values, just not for the selected PerID...so how do I get AccNo 300 to be included in my Query result?

This is my SQL Query:
SELECT AccountList.AccNo, PeriodBalance.PerID, PeriodBalance.PerBal
FROM AccountList LEFT OUTER JOIN

PeriodBalance ON AccountList.AccNo = PeriodBalance.AccNo
WHERE PeriodBalance.PerID = 2 OR ISNULL(PerID,4) = 4

Thanks in advance;





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

Join Only Returns The Read Rows :|

Nov 1, 2005

Hi all,

I am trying to build a association table (t2) to store a list of users
have viewed an item in my records table (t1). My goal is to send the
UserID parameter to the query and return to the user a read / not read
marker from the query so I can handle the read ones differently in my
.net code. The problem is that I cannot work out how to return anything
but the read data to the client. So far my stored proc looks like this

DECLARE @UserID AS Int -- FOR TESTING
SET @UserID = 219 -- FOR TESTING

SELECT t1.strTitle, t1.MemoID, Count(t2.UserID) AS ReadCount,t2.UserID

FROM t1
LEFT OUTER JOIN
t2 ON t1.MemoID = t2.MemoID

WHERE t2.UserID = @UserID

GROUP BY t1.MemoID, t1.strTitle,t2.UserID

It works fine but only returns those records from t1 that are read. I
need to return the records with null values also! I may have built the
assoc table wrong and would really appreciate some pointers on what I
am doing wrong. (assoc table has rID, MemoID and UserID columns)

Please help!

Many thanks

View 2 Replies View Related

Left Join Not Returning Rows

Nov 3, 2005

SELECT
[tblSections].[pageTitle],
[tblSections].[sectionURL],
[tblSectionContents].[articleID],
[tblSectionContents].[fileID],
[tblSectionContents].[linkID],
[tblCopy].[copyText],
[tblFiles].[fileName],
[tblFiles].[fileCaption],
[tblGroupings].[grouping],
[tblLinks].[linkURL]
FROM [tblSections]
LEFT JOIN [tblSectionContents] ON [tblSectionContents].[sectionID] = [tblSections].[id]
LEFT JOIN [tblCopy] ON [tblSectionContents].[articleID] = [tblCopy].[id]
LEFT JOIN [tblFiles] ON [tblSectionContents].[fileID] = [tblFiles].[id]
LEFT JOIN [tblGroupings] ON [tblFiles].[groupingID] = [tblGroupings].[id]
LEFT JOIN [tblLinks] ON [tblSectionContents].[linkID] = [tblLinks].[id]
WHERE [tblSections].[id]=2
ORDER BY
[tblSectionContents].[articleID],
[tblSectionContents].[fileID],
[tblSectionContents].[linkID]


If I pass it the ID of a section that has files or copy or [stuff in other tables] attached, then I get a result set that makes sense.

But if I pass it a section ID that doesn't reference any other content tables (ie: the section just has a title and a link URL), I don't get anything back.

Shouldn't it should still get me the fields from the row in tblSections that matches the ID I'm passing it?

How can I make it so that it does?

Thanks :)

View 3 Replies View Related

Join Returns Duplicate Rows

Oct 23, 2007

Hi,
I'm having a little trouble with the following code:

SELECT DISTINCT cd1.*, cd2.*
FROM Table1 cd1 LEFT JOIN Table2 cd2
ON cd1.RegNr=cd2.RegNr
WHERE cd1.RegNr = $RegNr

I want it to return the 2 rows that is present in the tables but it returns 4.

1262007-10-20 10:14:00
1262007-10-20 10:14:00
1262007-10-20 10:17:00
1262007-10-20 10:17:00

View 18 Replies View Related

INNER JOIN Between A CLR-TVF And A Table Returns No Rows

Feb 24, 2007

I have the following query:

select sq.*, p.numero, p.nombre
from paf p right outer join dbo.GetListOfSquaresForShippingLot(@lot) sq on sq.number = p.numero and sq.version = p.numero

The @lot parameter is declared at the top ( declare @lot int; set @lot = 1; ). GetListOfSquaresForShippingLot is a CLR TVF coded in C#. The TVF queries a XML field in the database and returns nodes as rows, and this is completed with information from a table.

If I run a query with the TVF only, it returns data; but if I try to join the TVF with a table, it returns empty, even when I'm expecting matches. I thought the problem was the data from the TVF was been streamed and that's why it could not be joined with the data from the table.

I tried to solve that problem by creating a T-SQL multiline TVF that is supposed to generate a temporary table. This didn't fix the problem.

What can I do? Does anybody know if I can force the TVF to render its data somewhere so the JOIN works? I was thinking a rowset function could help, but I just can't figure out how.

PLEASE HELP!!!!

Let me know if you want the code for the CLR TVF. This is the code for the T-SQL TVF:

CREATE FUNCTION [dbo].[GetTabListOfSquaresForShippingLot]
(
@ShippingLot int
)
RETURNS
@result TABLE
(
Number int, Version int, Position smallint,
SubModel smallint, Quantity smallint,
SquareId nvarchar(5),
ParentSquareId nvarchar(5),
IsSash smallint,
IsGlazingBead smallint,
Width float,
Height float,
GlassNumber smallint,
GlassWidth float,
GlassHeight float
)
AS
BEGIN
INSERT INTO @result
SELECT *
FROM dbo.GetListOfSquaresForShippingLot(@ShippingLot)

RETURN
END

View 6 Replies View Related

Merge Join - No Output Rows

Apr 24, 2008

Hi,

I have a problem with a Merge Join providing no output (when it should have 1890 rows). My Data Flow Task has 4 OLE Data Sources, 3 Multicasts, and 1 OLE Data Destination. I am experiencing the problem near the end of my data flow where two Multicasts create two parallel flows of data (see Level 1 below). I have two Merge Joins which join one leg from each multicast with a leg from the other multicast (see Level 2 below). Then the two remaining legs use a Merge to get my destination output (see Level 3 below).

I am experiencing my problem with the Merge Join (input A2, B2) --> (output C2) transformation. The Merge Join providing output C1 appropriately outputs 1890 rows, but C2 outputs 0 rows. Both Merge Joins are identical. The data is identically sorted prior to entering the problematic Merge Join and a DataViewer (Grid) verified that the data is appropriately entering in. Merge Join (input A2, B2) --> (output C2) has 667 rows as input A2 and 1890 rows as input B2 (using an inner join, just like the other merge join), but C2 baffles me with 0 rows of output (when it too should have 1890). I receive no Ouput errors and the execution completes showing all green.

Level 1
Multicast (output A1, A2) [667 rows]
Multicast (ouput B1, B2) [1890 rows]


Level 2
Merge Join (input A1, B1) --> (output C1) [1890 rows]
Merge Join (input A2, B2) --> (output C2) [0 rows]

Level 3
Merge (input C1, C2) --> (output D1) [1890 rows]*


I read about mysterious behavior with Merge Joins and have attempted modifying my EngineThreads property to values between 2 and 10, with no luck. Any help/ideas would be appreciated.

Thanks,

Devin

* Should be 3780 rows

View 4 Replies View Related

Selecting Distinct Top 3 Rows From Database Using Join

Jun 25, 2007

Hi guys,

Just trying to select a set of Articles from a SQL Server Database. The Articles all have a Category ID which is stored in another table (as an Article could be in more than one Category). I want to select the Top 3 Articles in a Category. At the moment I have as my SQL;

"SELECT TOP 3 f.ArticleID, f.Heading, f.Summary, f.WrittenDate, f.ArticleURL FROM feedTable f LEFT JOIN Categories c ON f.ArticleID = c.ArticleID WHERE c.CategoryID=" + CategoryID + " AND c.ArticleID<>" + id + " ORDER BY c.CategoryID"

Which seems to work to an extent in that I do get three articles in the same Category appearing. However, there are sometimes duplicates appearing, so I need to incorporate a DISTINCT clause to the above. I'm not sure where to put this in though. Any ideas?

Thanks.

View 6 Replies View Related

Join: Conditionally Include Data From Sub Rows?

Nov 2, 2004

Having one invoice table (ord) and one 'person' table (actor) I would like to include the name of the person who is responsible for an invoice: SELECT Ord.OrdNo, Ord.Selbuy, AC.Nm AS 'Responsible', AC.EmpNoFROM OrdLEFT OUTER JOIN Actor AS AC ON Ord.Selbuy = AC.EmpNoWHERE ord.ordno = 23505 This works perfectly fine if Ord.Selbuy has a corresponding value in Actor:|26914 |21|Yvonne| 21| or if there is no corresponding value in Actor:|26914 |21|NULL| NULL| But what if Ord.Selbuy=0? Then I end up with 3285 rows from Actor! This happens because Actor.EmpNo=0 is allowed. Persons which have never been employed or used to be employed gets Actor.EmpNo=0.Can I create a SELECT statement which only returns data from the INVOICE row if Ord.Selbuy=0?|26914 |21|NULL| NULL| p.s. I'm not able to change table structure/behavior of update procedures, because the tables/code belong to a "bought from the shelf"-business system.

View 2 Replies View Related

Duplicate Result Rows From 2 Table Join

May 7, 2012

I am using SLQ Server 2008 R2. The database was designed by another company.

I have two tables: Client and Client_Location. In the Client table the pk is Client_ID. There is also a unique key: sys_Client_ID. Both the Client_ID and the sys_Client_ID fields exist as a foreign keys in the Client_Location table. However, the fields are not noted as unique in the Client_Location table. There are two fields in the Client_Location table that determine when the address was effective. They are from_dt and end_dt.

Multiple records have been loaded into the Client_Location table to track old as well as current addresses of clients.

I'm trying to run a report that will pull clients with a plan_id constraint from the Client table and join the Client_Location table to retrieve the current address of these clients.

My SQL is:

select distinct (a.client_id), a.cli_last AS Last_Name,
a.cli_first AS First_Name, a.cli_middle AS Mid_Init,
b.city AS City, b.county AS County, b.state AS State
from ECBH.dbo.tbl_Client a inner join ECBH.dbo.tbl_Client_Location b
on a.client_id = b.client_id
inner join ECBH.dbo.tbl_client_insurance c
on a.client_id = c.client_id
inner join ECBH_TEST.dbo.tbl_GEF_County d
on b.county = d.COUNTY_NAME
where c.plan_id = 4
order by a.cli_last, a.cli_first

Because multiple records exist in the Client_Location table, the result set has duplicates. How can I pull only the results where the from_dt is most recent?

View 5 Replies View Related

Inner Join Returns Multiple Duplicated Rows

Dec 3, 2013

Here is my query which returns multiple rows

SELECT
R.name, R.age,R.DOB,
ISNULL(D.Doc1,'NA') AS doc1,
ISNULL(C.Doc2,'NA') AS doc2
FROM
REQ R
inner join RES S ON R.Request_Id=S.Request_Id
inner join RES1 D ON D.Response_Id=S.Response_Id
inner join REQ1 C ON C.Request_Id=R.Request_Id

select * from RES1 where Response_Id = 111 -- return 3
select * from REQ1 where Request_Id = 222 --- returns 2

So at last inner join retuns 3*2 = 6 records , which is wrong here and i want to show 3 records in doc1 row and 2 records in doc 2 rows ...

View 5 Replies View Related

Transact SQL :: Filter - Join Query Rows

Nov 14, 2015

Please refer to the below query. I want to filter inner join rows based on outer query column value (refer to bold text).

SELECT M.MouldId, SI.StockCode, MI.Cavity, MI.ShotCounter, CQ.SumOfCastedQty  as CastedQty, MI.CounterStartup 
FROM        MouldItem MI
JOIN (SELECT JD.MouldId, JC.StockCode, SUM(JS.CastedQty) AS SumOfCastedQty
FROM JobCasting AS JS INNER JOIN JobCreationDet AS JD ON JS.JobDetId = JD.Uniid INNER JOIN JobCreation AS JC ON JD.JobIdx = JC.Uniid

[Code] ....

View 2 Replies View Related

Why I Got Added Rows When Using FULL OUTER JOIN?

Nov 19, 2006

I've met a curiouse thing when using full outer join, that I got some rows belong to neither tables @_@

The SQL statement is like this:

SELECT     PreviousMonth.InvoiceID, PreviousMonth.CategoryName, PreviousMonth.ProdName, PreviousMonth.Qty, ISNULL(CurrentMonth.SellTotal, 0)
                      AS SellTotal, ISNULL(PreviousMonth.SellTotal, 0) AS PriorSellTotal


FROM         (SELECT     SellTotal, InvoiceID, CategoryName, ProdName, Qty
                       FROM          viewProdSales AS viewProdSales_1
                       WHERE      (DateCreated >= @pStartDate) AND (DateCreated <= @pEndDate))  AS CurrentMonth

FULL OUTER JOIN
                      (SELECT     SellTotal, InvoiceID, CategoryName, ProdName, Qty
                        FROM          viewProdSales
                        WHERE      (DateCreated >= @pPriorStartDate) AND (DateCreated < @pStartDate))  AS PreviousMonth

ON
                      CurrentMonth.InvoiceID = PreviousMonth.InvoiceID

 

The result include some added rows, if I query the 2 sub table seperately, neither contains such rows. 

For example, if I pass 01/09/2006, 01/10/2006 and 31/10/2006 as pPriorStartDate, pStartDate and pEndDate, to query the sales statistics in Sept and Oct, I would get some reords in June or even earlier...   Anyone know about this?  Thanks in advance.

 

Summer

 

 

View 3 Replies View Related

How To Remove Duplicate Rows From Full Join Query

Jan 26, 2008

I have 4 tables (SqlServer2000/2005). In the select query, I have FULL JOINED all the four tables A,B,C,D as I want all the data. The result is as sorted by DDATE desc:- 
AID     BID      BNAME          DDATE                                   DAUTHOR
1          1          abcxyz              2008-01-20 23:42:21.610        c@d.com
1          1          abcxyz              2008-01-20 23:41:52.970        a@b.com
1          2          xyzabc              2008-01-21 00:17:14.360        c@d.com
1          2          xyzabc              2008-01-20 23:43:17.110        a@b.com        
1          2          xyzabc              2008-01-20 23:42:43.937        a@b.com
1          2          xyzabc              NULL                                      NULL
2          3          pqrlmn              NULL                                      NULL
2          4          cdefgh              NULL                                      NULL 
Now, I want unique rows from the above result set like :- 
AID     BID      BNAME          DDATE                                   DAUTHOR
1          1          abcxyz              2008-01-20 23:42:21.610        c@d.com
1          2          xyzabc              2008-01-21 00:17:14.360        c@d.com
2          3          pqrlmn              NULL                                      NULL
2          4          cdefgh              NULL                                      NULL 
I want to remove the duplicate rows and show only the unique rows but contains all the data from the first table A. I have to bind this result set to a nested GridView.
 

View 8 Replies View Related

Table Join Statement Returns Repeat Rows

Jul 22, 2007

Hello All.

I am struggling with the below join block in my stored procedure.
I can't seem to get the duplicate row problem to go away. It seems that SQL is treating each new instance of an email address as reason to create a new row despite the UNIONs.
I understand that if I am using UNION, using DISTINCT is redundant and will not solve the duplicate row problem.

Primary Keys: none of the email address columns are primary keys. Each table has an incrementing ID column that serves
as the primary key.

I am guessing I am encountering this problem because of how
I have structured my Join statements? Is it possible to offer advice without a deeper understanding of my data model or
do you need more information?

Thanks for any tips.


Code:


select emailAddress from Users union
select user_name from PersonalPhotos union
select email_address from EditProfile union
select email_address from SavedSearches union
select distinct email_address from UserPrecedence union
select email_address from LastLogin) drv
Left Join Users tab1 on (drv.emailAddress = tab1.emailAddress)
Inner Join UserPrecedence tab5 on tab5.UserID=tab1.UserID
Left Join PersonalPhotos tab2 on (drv.emailAddress = tab2.user_name)
Left Join LastLogin tab4 on (drv.emailAddress = tab4.email_address)
Left Join EditProfile tab3 on (drv.emailAddress = tab3.email_address)
Left Join SavedSearches tab6 on (drv.emailAddress = tab6.email_address

View 8 Replies View Related

Display All Rows In Left Outer Join (was Would Be So Grateful For Sql Help)

Jan 20, 2005

This is what I want my results to look like

invoice wbs1 wbs2 amount
8060 000-333 500 0
8060 000-333 100 0
8060 000-333 140 0
8060 000-333 150 4335
8060 000-333 160 0
8267 000-333 500 0
8267 000-333 100 20500
8267 000-333 140 547.50
8267 000-333 150 2000
8267 000-333 160 5000


This is what I have so far:

SELECT PR.WBS1, PR.WBS2, ledgerar.invoice, SUM(CASE WHEN ledgerar.transtype = 'in' AND ledgerar.period = '200405' THEN ledgerar.amount * - 1 END) AS amount
FROM PR LEFT OUTER JOIN
LedgerAR ON LedgerAR.WBS1 = PR.WBS1 AND LedgerAR.WBS2 = PR.WBS2 AND LedgerAR.WBS3 = PR.WBS3
WHERE (LedgerAR.wbs1 = '001-333') AND ledgerar.period = '200405'
GROUP BY pr.wbs1, pr.wbs2, ledgerar.invoice


the above query gives me the following results:

invoice wbs1 wbs2 amount
8060 000-333 100 0
8060 000-333 140 0
8060 000-333 160 4335
8267 000-333 100 1320
8267 000-333 140 20912.5
8267 000-333 150 8363
8267 000-333 160 2650


But I don't know how to get the query to display all of wbs2 whether it is null or not. So, for each invoice number there should be five records according to the wbs2 codes (500, 100, 140, 150, 160)

Does anyone know how to do this?

Thanks,
Laura

View 1 Replies View Related







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