Getting Duplicates With Select Distinct (full Outer Join)

Aug 3, 2006

I am writing a script to create a audit trigger on any table. I am getting duplicate rows inserted into my audit table, only for the primary key columns. Anybody see why?

Right now I am debugging an Insert, so I think you can ignore the "U" update part of the Where clause.



....starts with other code to determine columns and primary key fields for selected table....

--get number of columns
select
@rowId = min(RowId),
@MaxRowId = max(RowId)
from #tblFieldNames

-- Loop through fields and build Sql string
while @RowId <= @MaxRowId
BEGIN
SELECT @fieldname = colName FROM #tblFieldNames WHERE RowId = @RowId

SELECT @sql = 'insert tblAuditAdmin (TableAltered, [Action], FieldName, OldValue, NewValue, UpdateDate, UpdateNumber, UserName)'
SELECT @sql = @sql + ' select distinct''' + @TableName + ''''
SELECT @sql = @sql + ',''' + @TriggerType + ''''
SELECT @sql = @sql + ',''' + @fieldname + ''''
SELECT @sql = @sql + ',convert(varchar(1000),d.' + @fieldname + ')'
SELECT @sql = @sql + ',convert(varchar(1000),i.' + @fieldname + ')'
SELECT @sql = @sql + ',''' + @UpdateDate + ''''
SELECT @sql = @sql + ', 1'
SELECT @sql = @sql + ',''' + @UserName + ''''
SELECT @sql = @sql + ' FROM #ins i FULL OUTER JOIN #del d'
SELECT @sql = @sql + @pkJoinClause
SELECT @sql = @sql + ' WHERE (''' + @TriggerType + ''' = ''I'')'
SELECT @sql = @sql + ' OR (''' + @TriggerType + ''' = ''D'')'
SELECT @sql = @sql + ' OR (''' + @TriggerType + ''' = ''U'' AND '
SELECT @sql = @sql + '((i.' + @fieldname + ' <> d.' + @fieldname + ')'
SELECT @sql = @sql + ' OR (''' + @fieldname + ''' in (Select colName from #primaryKeyFields))'
SELECT @sql = @sql + ' OR (i.' + @fieldname + ' IS NULL AND d.' + @fieldname + ' is NOT null)'
SELECT @sql = @sql + ' OR (i.' + @fieldname + ' IS NOT NULL AND d.' + @fieldname + ' is null)))'

EXEC (@sql)

set @RowId = @RowId + 1
END

View 5 Replies


ADVERTISEMENT

Right Outer Join And Distinct

Dec 15, 2014

I have a view which joins 2 tables together in a left outer join.

Now, the left outer join table (lets call this SalesData) may or may not have records. As months and years go by, records will be inserted or updated.

I am trying to find a query which will do the following:

Bring back all records where the branch matches an input value and also:

- bring back NULL records for the YR and MO column
- bring back values which match the input params for YR and MO column.

this works as expected:

quote:
SELECT wmtecp.*
FROM v_stores wmtecp
RIGHT OUTER JOIN v_Stores roj ON wmtecp.ID = roj.ID
WHERE wmtecp.TM = @p1 AND 1=1 AND roj.YR IS NULL AND roj.MO IS NULL OR wmtecp.MO = 11 AND wmtecp.YR = 2014

This is right outer joining the view to itself and prefer it this way.

Here is the thing: I want to bring back only distinct records (distinct by store ID I guess).

We are bringing back result set which contains NULL and NON null values but for both result sets the same storeID is returned, I do not want this but to only bring back the same record once either WITH values or WITHOUT values.

View 1 Replies View Related

Merge Join (Full Outer Join) Never Finishes.

Jun 5, 2006

I have a merge join (full outer join) task in a data flow. The left input comes from a flat file source and then a script transformation which does some custom grouping. The right input comes from an oledb source. The script transformation output is asynchronous (SynchronousInputID=0). The left input has many more rows (200,000+) than the right input (2,500). I run it from VS 2005 by right-click/execute on the data flow task. The merge join remains yellow and the task never finishes. I do see a row count above the flat file destination that reaches a certain number and seems to get stuck there. When I test with a smaller file on the left it works OK. Any suggestions?

View 3 Replies View Related

Full Outer Join

Nov 1, 2005

helloi know that this post is not related to asp.net forum but if anyone can help me.i have made three sql tables called table1,table2 and table3.each one contains primary field called employeeidtable1 contains in addition to the primary a field callled field1.table2 contains in addition to the primary a field callled field2.table3 contains in addition to the primary a field callled field3.the first time table1 contains one record     employeeid  field1    ------------ ------      1353            abcthe second table contains no datathe third table contains also one record employeeid     field3    ------------ ------      1353            defi have made a query :select field1,field2,field3 from table1full outer join table2 on table1.employeeid=table2.employeeidfull outer join table3 on table2.employeeid=table3.employeeidthe result is :field1          field2     field3abc            null         nullnull             null         def  when i delete the record from the first table and put it in the second empty table:the result :field1          field2     field3null           abc        defi need to understand the results ?i know that the outer join will get the rows from the both tables,but the results how can i get i don't understandthank you for the help     

View 1 Replies View Related

FULL OUTER JOIN

May 23, 2006

This FULL OUTER JOIN seems inconsistent between two SELECT statements—it works right for one, but not for another, which is virtually identical (see below). I am looking for missing records, and the problem is that the NULL half of the joined record is showing up for one case, but NOT showing up for the other, as it should.
 
Fields A, B, C, D1, and D2 make up the complete primary key in table X (in that order) while fields A, C, and D make up the complete primary key in table Y (in that order). The example below works correctly for the first, but not for the second (all other SQL-Statement details are exactly identical).
 
… FROM X FULL OUTER JOIN Y ON X.A=Y.A AND X.C=Y.C AND X.D2=Y.D …
… FROM X FULL OUTER JOIN Y ON X.A=Y.A AND X.C=Y.C AND X.D1=Y.D …
 
The value 1 exists for Y.D, but is missing from both D1 and D2 in table X (matching values for A and C exist in both tables). Again, the problem is that the null, outer-joined record shows up only in the first example above.
 
The only difference I can see in the schema is that D2 is the last element of the primary key of X (and it works OK), while D1 is the second to last element of the same primary key (and it does not work). All key elements are INTEGER fields in SQL SERVER. For this test case I currently have no indexes in the database.
 
Does this look like a SQL-Server bug? am I missing something? help! I don't know how to work around this.
 

View 6 Replies View Related

Full Outer Join??

Nov 5, 2007

Hello!!

i have two tables

scanner_input:
id | quantity | status
-----------------------------------
prod1 | 6 | OK
prod2 | 7 | OK
prod3 | 3 | P
prod4 | 3 | OK
prod5 | 3 | OK
prod7 | 3 | OK


and

sap_input:
id | quantity | status
-----------------------------------
prod1 | 6 | OK
prod2 | 7 | OK
prod3 | 3 | P
prod4 | 2 | OK
prod6 | 3 | OK
prod8 | 3 | OK

i need a query to join both tables and compare the quantities of an item in table SCANNER_INPUT with its
corresponding item in SAP_INPUT, so the result would be something like this:

sap_input
id(scanner)| qty(scan)| id(sap) | qty(sap) | difference
------------------------------------------------------------
prod1 | 6 | prod1 | 6 | 0
prod2 | 7 | prod2 | 7 | 0
prod3 | 3 | prod3 | 3 | 0
prod4 | 3 | prod4 | 2 | 1
prod5 | 3 | prod5 | | 3
prod6 | | prod6 | 3 | -3
prod7 | 3 | prod7 | | 3
prod8 | | prod8 | 3 | -3


I found i can use a full outer join... but i dont know how to use it.

any ideas??

thnx

View 15 Replies View Related

SQL Full Outer Join

Jul 20, 2005

I have the following query:SELECT dbo.tSymExch.exCode, dbo.tSymGrp.sgCode,dbo.tSymMain.smCodeFROM dbo.tSymExch FULL OUTER JOINdbo.tSymGrp ON dbo.tSymExch.exID =dbo.tSymGrp.sgexID FULL OUTER JOINdbo.tSymMain ON dbo.tSymGrp.sgID =dbo.tSymMain.smsgIDWhich produces:exCodesgCodesmCodeCBOTCBOTTRSCB2NCBOTCBOTTRSCB30BCBOTCBOTTRSCB10NCBOTCBOTTRSCB5NCBOTCBOTEQCMEI want it to produce:exCodesgCodesmCodeCBOTCBOTTRSCB2NCBOTCBOTTRSCB30BCBOTCBOTTRSCB10NCBOTCBOTTRSCB5NCBOTCBOTTRSCBOTCBOTEQCBOTCME

View 7 Replies View Related

Full Outer Join

Oct 26, 2006

Hi,

i want to replace a

full outer join statement .

how do i?

i am more in control with '='

thanks/

View 8 Replies View Related

Full Outer Join On A Union?

Nov 28, 2007

Can i do a Full outer join on a union? and if so how?

I have this stored procedure. but then i was notified that they want to show all the sales reps, even if they dont have visits, and all the activities, even if neither has values. Right now this is what it shows:

Sales Rep. Visits Vacation Sick

Bob Smith 2 5 0

Julie Troy 1 0 1

Stefani Gray 1 0 0


--------------
I want it to look like this

Sales Rep. Visits Vacation Sick Drive-with Seminar Office-day Meeting
Bob Smith 2 5 0 0 0 0 0
Tod Taylor 0 0 0 0 0 0 0
Matt Mathews 0 0 0 0 0 0 0
Julie troy 1 0 1 0 0 0 0
Stefani Gray 1 0 0 0 0 0 0

heres my code:



Code Block
ALTER PROCEDURE [dbo].[PROC_DAILY_ACTIVITY]
(@Region_Key int=null)
AS
BEGIN

SELECT
NULL as Progress_time,
NULL As completed_time,
NULL as Dial_in_date,
NULL AS Customer_Code,
Non_Customer_Activities.question_code,
Non_Customer_Activities.description,
Sales_Group.Region,
Sales_Group.Name AS Territory_Name,
Non_Customer_Activities.Que_Desc AS Store_Name,
Non_Customer_Activities.Logged_Time AS TheDate,
CONVERT(FLOAT,Non_Customer_Activities.Logged_Time) Float_Date,
Non_Customer_Activities.response AS Response,
NULL AS is_Visit_Fg
FROM Qry_Sales_Group AS Sales_Group INNER JOIN
(SELECT QH.question_code, Question_Header.description, CONVERT(datetime, DATEADD(day, QH.cycle_day - 1, P.start_date), 6) AS Logged_Time,
SUBSTRING(QH.entity_code, 1, 5) AS SR_Code, QH.response, Territory_In_Sales_Responsible.Territory_Code AS SR_Territory_Code,
'Not Customer Related' AS Que_Desc
FROM question_history AS QH INNER JOIN
period AS P ON P.period_code = QH.period_code INNER JOIN
RC_DWDB_INSTANCE_1.dbo.Tbl_Territory_In_Sales_Responsible AS Territory_In_Sales_Responsible ON
Territory_In_Sales_Responsible.SalesPerson_Purchaser_Code = SUBSTRING(QH.entity_code, 1, 5) COLLATE Latin1_General_CI_AS INNER
JOIN
questions AS Question_Header ON Question_Header.question_code = QH.question_code
WHERE (QH.entity_code LIKE '%.USER%') AND (Question_Header.question_code IN ('AME01', 'ASE01', 'ACO01', 'ALU01', 'AOS01', 'APH01',
'ATR01', 'ATE01', 'ACR06', 'ACR05', 'ACR02', 'ACR03', 'ACR08', 'ACR07')) AND (CONVERT(datetime, DATEADD(day, QH.cycle_day - 1,
P.start_date), 6) = case
when Datepart(Weekday, Getdate()) = 2 then datediff(dd,0,GetDate()) - 3
else datediff(dd,0,GetDate()) - 1
end )) AS Non_Customer_Activities
ON Sales_Group.Code = Non_Customer_Activities.SR_Territory_Code
WHERE Region_Key=@Region_Key
UNION ALL
SELECT
in_progress_time,
completed_time ,
dial_in_date,
Customer_Activities.Customer_Code,
NULL AS Expr1,
NULL AS Expr2,
Sales_Group.Region,
Sales_Group.Name AS Territory_Name,
Customer_Activities.Customer_Name AS Store_Name,
Customer_Activities.Logged_Time AS TheDate,
CONVERT(FLOAT,Customer_Activities.Logged_Time) Float_Date,
NULL AS Response,
Customer_Activities.Is_Visit_Fg
FROM Qry_Sales_Group AS Sales_Group INNER JOIN
(SELECT DISTINCT in_progress_time,completed_time,dial_in_date,
V.visit_date AS Logged_Time, Customer_Code, customer_name AS Customer_Name,
Territory_In_Sales_Responsible.Territory_Code AS Cust_Territory_Code, 1 AS Is_Visit_Fg
FROM Qry_visits AS V
INNER JOIN RC_DWDB_INSTANCE_1.dbo.Tbl_Territory_In_Sales_Responsible AS Territory_In_Sales_Responsible ON
Territory_In_Sales_Responsible.SalesPerson_Purchaser_Code = V.sales_person_code COLLATE Latin1_General_CI_AS
INNER JOIN FSSRC.dbo.Communication_statistics as Communication
ON Communication.sales_person_code=Territory_In_Sales_Responsible.SalesPerson_Purchaser_Code COLLATE Latin1_General_CI_AS
WHERE (CONVERT(datetime, CONVERT(Varchar, V.visit_date, 110)) = case
when Datepart(Weekday, Getdate()) = 2 then datediff(dd,0,GetDate()) - 3
else datediff(dd,0,GetDate()) - 1
end )

) AS Customer_Activities ON
Sales_Group.Code = Customer_Activities.Cust_Territory_Code
WHERE Region_Key=@Region_Key
end

View 5 Replies View Related

HELP... Need Work Around For FULL OUTER JOIN TSQL Using CE???

Mar 6, 2008



Hey all,

Anyone have a work around for using a TSQL FULL OUTER JOIN in CE? Something like a Right and a Left Outer Join for the below?

Thanks,
billb

Here's an example:


' Connection To SQL CE

Dim ConsqlShipTo As New SqlCeConnection

ConsqlShipTo.ConnectionString = "Data Source = " & Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) & "CRM.sdf"

'

'TSQL STATEMENT......

Dim reqSQL As New SqlCeCommand

reqSQL.CommandText = "SELECT " & _

" COALESCE(ShipTo.ShipToCust, Prospect.ProspectCust) AS [Customer ID], " & _

" COALESCE(ShipTo.ShipToName, Prospect.ProspectName) AS Name, " & _

" COALESCE(ShipTo.ShipToCity, Prospect.ProspectCity) AS City " & _

" FROM ShipTo FULL OUTER JOIN " & _

" Prospect ON ShipTo.ShipToName LIKE Prospect.ProspectName AND Prospect.ProspectCust LIKE ShipTo.ShipToCust " & _

" WHERE " & _

" (Prospect.Alias = '" & reqGetUserName & "' AND Prospect.ProspectName LIKE '%" & reqSearch & "%') " & _

" OR (ShipTo.Alias > '%%' OR ShipTo.Alias IS NULL) " & _

" AND (ShipTo.ShipToName LIKE '%" & reqSearch & "%') " & _

" GROUP BY " & _

" ShipTo.ShipToCust, Prospect.ProspectCust, ShipTo.ShipToName, Prospect.ProspectName, " & _

" ShipTo.ShipToCity, Prospect.ProspectCity " & _

" ORDER BY Name "

reqSQL.CommandType = CommandType.Text

reqSQL.Connection = ConsqlShipTo

ConsqlShipTo.Open()

'

'CREATE NEW SQL DATA ADAPTER

Dim sqlda As New SqlCeDataAdapter(reqSQL)

'

' FILL DATASET

Dim sqlds As New DataSet

sqlda.Fill(sqlds, "Customer ID")

'

' FILL DATATABLE - lightweight

Dim sqldt As New DataTable

sqlda.Fill(sqldt)

View 4 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 Can A Full Outer Join Be Done In A Data Flow Task?

Mar 28, 2008

I have a series of tasks that end up with two record sets that are unrelated which I would like to join. The first record set contains a list of expense accounts and the second record set contains a list of offices. I would like to create a join between the two sets where the resulting record set is a list of every office having every expense account.

If the data were in tables i'd create a sql statement something like this

Select t1.Account, t2.Office
from Table1 t1
Full Outer Join Table2 t2
on 1 = 1

That would give me the results I'm looking for however I can't find how to do this when these data sets are from the results of two different flows of data flow tasks.

Any ideas?
Thanks
Bill Webster

View 4 Replies View Related

Replacing SELECT With A Value In An OUTER JOIN

Sep 6, 2005

Hi All,I'm confused by how to replace a SELECT statement in a SQL statementwith a specific value. The table I'm working on is a list of words (acolumn called "word") with an index int pointing to the sentence theycome from (a column called "regret"). I also have a table of stop words(called "GenericStopWords") that contains the words I do not want toconsider. That table has a single column called "word".I started off using a SQL function (called "GETALLWORDS") whichreturned the words of a string. This is how I used it:INSERT INTO WordsSELECT wrds.WORD, 1 FROMGETALLWORDS('I could be bounded in a nutshell and count myself a kingof infinite space', default) AS wrdsLEFT OUTER JOINGenericStopWordsON wrds.WORD = GenericStopWords.wordWHERE GenericStopWords.word IS NULLThis statement inserts every word in the sentence that is not a stopword. So, for example, ('bounded', 1) is added but ('could', 1) is notadded.I've now decided to move the function that breaks a string into wordsout of the SQL layer of my application and into the JavaScript whichruns under ASP on the web server. So now I want to call somethinganalogous to the above SQL statement, but word by word. What I'd likeis something like:INSERT INTO WordsSELECT 'bounded', 1 FROM ???LEFT OUTER JOINGenericStopWordsON 'bounded' = GenericStopWords.wordWHERE GenericStopWords.word IS NULLDoes that make sense? I want a SQL statement that will insert the tuple('bounded', 1) into the table Words if (and only if) 'bounded' does notappear in the table GenericStopWords. It's easy to say procedurally, Icannot see how to write it in a relational style in SQL.Thanks in advance for any help you can give.Cheers,Tim.

View 3 Replies View Related

Sub-select Vs. LEFT OUTER JOIN

May 11, 2007

I think it is quite often when you need to view some records, which refer (by key) to data in other tables. For instance, a user belongs to a group but it is preferable to show group name in the user data rather than group id. The options are

1) LEFT OUTER JOIN:
SELECT users.id, groups.name FROM users LEFT OUTER JOIN groups ON users.[group] = groups.id

2) A Subselect:
SELECT id, [group] = (SELECT [name] FROM groups WHERE id = users.[group]) FROM users

Which is better and why?

View 2 Replies View Related

Unary Select On Items IF Then Else Outer Join ??

Apr 17, 2008

I have a table of products, and many products have the same name only they are different sizes. I want to only select a particular size like 20 oz, but if it does not exist in that size I want to select the next appropriate size (and which case if it does not exist i wish to select the next appropriate size and so on ..
Does any one know how I can accomplish this and would be willing to help me out by posting some code, some direction ??

View 15 Replies View Related

SQL-92 Outer Join Vs T-SQL Outer Join (6.5 Or 7.0) - Test Script Included

Apr 26, 2002

Take the following scenario:

We have two tables that have somewhat of a parent-child relationship. We are trying to use a SQL-92 outer join that returns the same results as a TSQL *= outer join. The difficulty we are having is that some of the parent records do not have any corresponding child records, but we still want to see those parent records with 0 (zero) for the count. How can we accomplish this with a SQL-92 compliant join (if it is even possible)? In the query results below, we would like the first set of results.

Thanks in advance for any help.
-David Edelman

Test script below, followed by results
===========================================
create table parent (p_id int NOT NULL)
go
create table child (p_id int NOT NULL, c_type varchar(6) NULL)
go
insert parent values (1)
insert parent values (2)
insert parent values (3)
insert parent values (4)
insert parent values (5)
insert parent values (6)
insert parent values (7)
insert parent values (8)
insert parent values (9)
insert parent values (10)
go

insert child values (1, 'AAA')
insert child values (1, 'BBB')
insert child values (1, 'CCC')
insert child values (2, 'AAA')
insert child values (4, 'AAA')
insert child values (4, 'DEF')
insert child values (4, 'AAA')
insert child values (4, 'BBB')
insert child values (5, 'AAA')
insert child values (5, 'AAA')
insert child values (6, 'AAA')
insert child values (7, 'AAA')
insert child values (7, 'BBB')
insert child values (7, 'CCC')
insert child values (7, 'DDD')
insert child values (10, 'AAA')
insert child values (10, 'CCC')
go

select p.p_id, count(c.p_id) as num_rows
from parent p, child c
where p.p_id *= c.p_id
and c.c_type in ('AAA', 'BBB')
group by p.p_id

select p.p_id, count(c.p_id) as num_rows
from parent p left outer join child c on p.p_id = c.p_id
where c.c_type in ('AAA', 'BBB')
group by p.p_id

=========================================
Results:
(T-SQL *= outer join)
p_id num_rows
----------- -----------
1 2
2 1
3 0
4 3
5 2
6 1
7 2
8 0
9 0
10 1

(SQL-92 outer join)
Warning: Null value eliminated from aggregate.
p_id num_rows
----------- -----------
1 2
2 1
4 3
5 2
6 1
7 2
10 1

View 1 Replies View Related

SELECT DISTINCT With JOIN

Jul 20, 2005

Hi everyoneHave a problem I would areally appreciate help with.I have 3 tables in a standard format for a Bookshop, egProductsCategoriesCategories_Productsthe latter allowing me to have products in multiple categories.Everthing works well except for one annoying little thing.When an individual product (which is in more than one topcategory) is addedto the Shopping Cart it displays twice, because in my select statement Ihave the Category listed. I realise I could remove the TopCategory from thestatement and that makes my DISTINCT work as I wanted, but Id prefer to havethe TopCategory as it saves me later having to another SQL query (Im alreadydoing one to allow me not to list category in the Statement .... but If Ican overcome this one ... then I can remove this as well).Here is my table structure (the necessary bits)productsidProduct int....categoriesidcategory intidParentCategory inttopcategory int...categories_productsidCatProd intidProduct intidCategoryWhen I run a query such asSELECT DISTINCT a.idProduct, a.description,a.descriptionLong,a.listPrice,a.price,a.smallImageUrl,a.stock, a.fileName,a.noShipCharge,c.topcategoryFROM products a, categories_products b, categories cWHERE active = -1 AND homePage = -1AND a.idProduct = b.idProductAND c.idcategory=b.idcategoryAND prodType = 1 ORDER BY a.idProduct DESCThis will return all products as expected, as well as any products which arein more than one TopCategory.Any ideas how to overcome this would be greatly appreciated.CheersCraig

View 14 Replies View Related

Select DISTINCT In LEFT JOIN

Feb 14, 2008

Hi again,
I have this SQL (part of a stored procedure) where I do LEFT JOIN. SELECT callingPartyNumber, AlertingName, originalCalledPartyNumber, finalCalledPartyNumber,
dateTimeConnect,
dateTimeDisconnect,
CONVERT(char(8), DATEADD(second, duration, '0:00:00'), 108) AS duration,
clientMatterCode


FROM CDR1.dbo.CallDetailRecord t1
LEFT JOIN CDR2.dbo.NumPlan t2 ON t1.callingPartyNumber=t2.DNorPattern

WHERE
(t1.callingPartyNumber LIKE ISNULL(@callingPartyNumber, t1.callingPartyNumber) + '%') AND
(t1.originalCalledPartyNumber LIKE ISNULL(@originalCalledPartyNumber, t1.originalCalledPartyNumber) + '%') AND
(t1.finalCalledPartyNumber LIKE ISNULL(@finalCalledPartyNumber, t1.finalCalledPartyNumber) + '%') AND
(t1.clientMatterCode LIKE ISNULL(@clientMatterCode, t1.clientMatterCode) + '%') AND
(@callerName is NULL OR t2.AlertingName LIKE '%' + @callerName + '%') AND
(t1.duration >= @theDuration) AND
((t1.datetimeConnect) >= ISNULL(convert(bigint,
datediff(ss, '01-01-1970 00:00:00', @dateTimeConnect)), t1.datetimeConnect)) AND
((t1.dateTimeDisconnect) <= ISNULL(convert(bigint,
datediff(ss, '01-01-1970 00:00:00', @dateTimeDisconnect)), t1.dateTimeDisconnect))
 The problem is that if the t2 has more than one entry for the same DNorPattern, it pulls the record more than once. So say t1 has a callingPartyNumber = 1000. t2 has two records for this number. It will pull it more than once. How do I get the Unique value.
What I am trying to get is the AlertingName (name of the caller) field value from t2 based on DNorPattern (which is the phone number).
If this is not clear, please let me know.
Thanks,
Bullpit 

View 24 Replies View Related

Stored Procedure - Select Distinct And Inner Join

Nov 16, 2006

I've been trying to get this to work right.
The db table has 3 fields: id, vwr, and reqType.
I need all DISTINCT vwr's from the table. (vwr's can repeat)
This gives me all rows, not distinct...
 select distinct d.id, d.vwr, d.reqType from tblVWR AS dinner join tblVWR ton d.vwr = t.vwr
Any suggestions?
Thanks,
Zath

View 2 Replies View Related

Transact SQL :: Difference Between Outer Apply And Outer Join

May 10, 2010

what is difference between outer apply and outer join ,both return rows from left input as well as right input . isnt it?

View 3 Replies View Related

Can Any One Tell Me The Difference Between Cross Join, Inner Join And Outer Join In Laymans Language

Apr 30, 2008

Hello

Can any one tell me the difference between Cross Join, inner join and outer join in laymans language

by just taking examples of two tables such as Customers and Customer Addresses


Thank You

View 1 Replies View Related

LEFT OUTER JOIN Or RIGHT OUTER JOIN?

Nov 4, 2003

Hello

I've a table with these values:

Cod_Lingua - Des_Lingua
------------------------------
ITA Italian
GER German
ENG English
FRA French

and another table with product/description

ProductID - Cod_Lingua - Description
-------------------------------------------
1 ITA Mia Descrizione
1 ENG My Description

I've this SELECT:

SELECT Tab_Lingue.Cod_Lingua, Descrizioni_Lingua.Description
FROM Descrizioni_Lingua RIGHT OUTER JOIN Tab_Lingue ON Tab_Lingue.Cod_Lingua=Descrizioni_Lingua.Cod_Lingua
WHERE Descrizioni_Lingua.ProductID=1

I get these results:
ITA - Mia Descrizione
ENG - My Description

I don't want this. I'd like to have this:
ITA - Mia Descrizione
ENG - My Description
GER - (null)
FRA - (null)

How can I get the second result set?

Thanks for your support.

View 3 Replies View Related

Transact SQL :: Difference Between Inner Join And Left Outer Join In Multi-table Joins?

Oct 8, 2015

I was writing a query using both left outer join and inner join.  And the query was ....

SELECT
        S.companyname AS supplier, S.country,P.productid, P.productname, P.unitprice,C.categoryname
FROM
        Production.Suppliers AS S LEFT OUTER JOIN
        (Production.Products AS P
         INNER JOIN Production.Categories AS C

[code]....

However ,the result that i got was correct.But when i did  the same query using the left outer join in both the cases

i.e..

SELECT
        S.companyname AS supplier, S.country,P.productid, P.productname, P.unitprice,C.categoryname
FROM
        Production.Suppliers AS S LEFT OUTER JOIN
(Production.Products AS P
LEFT OUTER JOIN Production.Categories AS C
ON C.categoryid = P.categoryid)
ON
S.supplierid = P.supplierid
WHERE
S.country = N'Japan';

The result i got was same,i.e

supplier     country    productid    productname     unitprice    categorynameSupplier QOVFD     Japan     9     Product AOZBW    97.00     Meat/PoultrySupplier QOVFD    Japan   10     Product YHXGE     31.00     SeafoodSupplier QOVFD     Japan   74     Product BKAZJ    10.00     ProduceSupplier QWUSF     Japan    13     Product POXFU     6.00     SeafoodSupplier QWUSF     Japan     14     Product PWCJB     23.25     ProduceSupplier QWUSF    Japan     15    Product KSZOI     15.50    CondimentsSupplier XYZ     Japan     NULL     NULL     NULL     NULLSupplier XYZ     Japan     NULL     NULL     NULL     NULL

and this time also i got the same result.My question is that is there any specific reason to use inner join when join the third table and not the left outer join.

View 5 Replies View Related

'Left Outer Merge Join' Failing To Join Valid Row

Aug 10, 2007

Scenario:

OLEDB source 1
SELECT ...
,[MANUAL DCD ID] <-- this column set to sort order = 1
...
FROM [dbo].[XLSDCI] ORDER BY [MANUAL DCD ID] ASC


OLEDB source 2
SELECT ...
,[Bo Tkt Num] <-- this column set to sort order = 1
...
FROM ....[dbo].[FFFenics] ORDER BY [Bo Tkt Num] ASC

These two tasks are followed immediately by a MERGE JOIN

All columns in source1 are ticked, all column in source2 are ticked, join key is shown above.
join type is left outer join (source 1 -> source 2)

result of source1 (..dcd column)
...
4-400-8000119
4-400-8000120
4-400-8000121
4-400-8000122 <--row not joining
4-400-8000123
4-400-8000124
...


result of source2 (..tkt num column)
...
4-400-1000118
4-400-1000119
4-400-1000120
4-400-1000121
4-400-1000122 <--row not joining
4-400-1000123
4-400-1000124
4-400-1000125
...

All other rows are joining as expected.
Why is it failing for this one row?

View 1 Replies View Related

Select DISTINCT On Multiple Columns Is Not Returning Distinct Rows?

Jul 6, 2007

Hi, I have the following script segment which is failing:

CREATE TABLE #LatLong (Latitude DECIMAL, Longitude DECIMAL, PRIMARY KEY (Latitude, Longitude))

INSERT INTO #LatLong SELECT DISTINCT Latitude, Longitude FROM RGCcache



When I run it I get the following error: "Violation of PRIMARY KEY constraint 'PK__#LatLong__________7CE3D9D4'. Cannot insert duplicate key in object 'dbo.#LatLong'."



Im not sure how this is failing as when I try creating another table with 2 decimal columns and repeated values, select distinct only returns distinct pairs of values.

The failure may be related to the fact that RGCcache has about 10 million rows, but I can't see why.

Any ideas?

View 2 Replies View Related

Inner Join To Outer Join Problem

Mar 1, 2008

hello, i am running mysql server 5 and i have sql syntax like this:
select
sales.customerid as cid,
name,
count(saleid)
from
sales
inner join
customers
on
customers.customerid=sales.customerid
group by
sales.customerid
order by
sales.customerid;
it works fine and speedy. but when i change inner join to right join, in order to get all customers even there is no sale, my server locks up. note: there is about 10000 customers and 15000 sales.
what can be the problem?
thanks,

View 10 Replies View Related

Self Join Outer Join Question

Oct 10, 2007

Given a table of building components e.g. floors, walls, etc, etc:

create table component_multiplier_table
(

system_code char(4),
system_component_code char(3),
function_code char(4),
component_multiplier dec(7,6)
)

Where function_code is the function of the area e.g. Auditorium, Classrom, etc, etc. And not all components are available for all functions e.g. Carpeting is available for Classrooms but not Power Plants or Warehouses.

I need to self join the above table to itself on system_code and system_component_code and find out which rows are missing from each side.

A query that I've been banging away at with no success is:

SELECT c1.*, c2.*
FROM [dbo].[component_multiplier_table] c1 FULL OUTER JOIN [dbo].[component_multiplier_table] c2
ON (c1.system_component_code = c2.system_component_code) AND (c1.[system_code] = c2.[system_code])
WHERE c1.function_code = '2120' AND c2.[function_code] = '2750' AND (c1.[system_code] IS NULL OR c2.system_code IS NULL);

I added the is null conditions, no joy. I've tried every flavor of outer join w/o success.

Could any T-SQL gurus out there help me figure out how to do this in a set before I start coding

DECLARE crsr CURSOR

Thanks.

View 7 Replies View Related

Left Join Vs Left Outer Join Syntax Generates Different Execution Plans

Apr 16, 2008



Anyone know why using

SELECT *
FROM a LEFT OUTER JOIN b
ON a.id = b.id
instead of

SELECT *
FROM a LEFT JOIN b
ON a.id = b.id

generates a different execution plan?

My query is more complex, but when I change "LEFT OUTER JOIN" to "LEFT JOIN" I get a different execution plan, which is absolutely baffling me! Especially considering everything I know and was able to research essentially said the "OUTER" is implied in "LEFT JOIN".

Any enlightenment is very appreciated.

Thanks

View 5 Replies View Related

Help Selecting Duplicates - Added In Full Query

Oct 15, 2007

[SELECT coalesce(a4.key,a3.key,a2.key,a.key) as parent_key,
a.key as child_key,
a.comp_name
FROM .......lots of JOINS..........]

that's what I have, and I need to find all instances where parent_key=child_key.

I've been trying something similiar to...

[SELECT name, count(name), name2, count(name2)
FROM people
GROUP BY name, name2
HAVING (count(name)>1 AND count(name2)>1)]

The problem is that I keep getting error messages because I can't use
the alias' or sum(coalesce(.....)).

I was hoping you guys might have a suggestion for me. Thanks ahead of time.

View 10 Replies View Related

Full Outer Joins Supported? Unsupported?

Mar 12, 2007

 

Has anyone tried using a TSQL full outer join and managed to get it working? Any documentation for Full Outer Joins in CE?

 

Any ideas? Thanks, Bill

View 1 Replies View Related

Self-Join Duplicates - Help!

Oct 22, 2004

Can some kind person out there please help me, I've been stuck on this for daaaa-y-s.

I have a database that allows users to search for pdf's of technical drawings.

Basically I have one huge table with multiple columns, which the user can only search on any combination of one of these two columns
"drawing_series" eg 0100, 0046, 1000
"drawing_number" eg 0076000, 0000123, 0000004

There is also a Revision column(which the user can't see) that goes up by 1 each time a drawing has been modified and resubmitted to the database.
"revision" eg 01, 02, 03, ....... 99

So a search on 0046 series might pull back drawings

0046-0010000-01
0046-0010000-02
0046-0010000-03
0046-0076000-01
0046-0076888-01
0046-0076888-02

The problem is that I only want drawings with the highest revisions returned eg

0046-0010000-03
0046-0076000-01
0046-0076888-02

The code below worked like a charm in the test stages pulling back a few hundred records but now that i've uploaded 10's of thousands of records to the DB the whole lot dies if the search result pulls back more than a few thousand records.

SELECT * FROM dbo.Drawing_Database
where dbo.Drawing_Database.revision=(select max(revision) from dbo.Drawing_Database self where self.drawing_series + self.drawing_number = dbo.Drawing_Database.drawing_series + dbo.Drawing_Database.drawing_number) Drawing_Series like '0046' order by Drawing_Series, Drawing_Number

There must be a simpler way of doing this as i can pull out duplicate series + numbers using " HAVING Count(*)>1" but dont know where to go from there.

Help!
TheMaster

View 2 Replies View Related

Help With A Join And Duplicates?

Jul 23, 2005

Hi All,I am banging my head against a brick wall over this problem, so anyhelp in the correct direction would be muchly appreciated!I have 2 SQL (MS SQL) server tables, realated to -a Property,Sales of that property.A property is uniquely identifed by its Roll, valuation Number andSuffix (not my choosing).Each property can only appear in the property table once, and can onlyhave 1 assessment - but can have multiple sales (ie - over theannalysis period the same property can sell more than once).There is approximatly 19000 properties relating to about 8000 sales.When creating a query to list property and most recent sale (if thereis any) I end up with somthing like this -SELECT [roll], [valuation], [suffix], [sale date]FROM [property]LEFT JOIN [sales]ON[property].[roll] = [sales].[roll] AND[property].[valuation] = [sales].[valuation] AND[property].[suffix] = [sales].[suffix](table names simplifed).I get rows where there is all the property data there, but sale date(etc.) is null (as I would expect from a left join), but the problem is- when there is more than 1 sale for a property it pulls out anothercopy of the property data.In short, because of that I come out with more records than properties.ie -roll valuation suffix sale date12 456789 A 1/1/200312 788988 B NULL14 123456 A 1/1/200314 123456 A 1/1/2004(Note - the last two are the same property).I didn't know that the left join can affect both joined tables!Is there any way around this? Any suggestions/hints in the rightdirection would be very much appreciated!THANKS!

View 3 Replies View Related

One To Many Join Causes Duplicates

Jul 20, 2005

When I run the attached query, I get duplicates when there is one tomany relationship between tableA and tableB. The query, tested schemaand the result is attached. Sorry for the long post.Here is tested Schema and Data inserts.----------------------create table TestTblA(ShipDate datetime,CPEID varchar(30),phonenum char(14))gocreate table TestTblB(CPEID varchar(30),itemID varchar(30),active char(1))gocreate table TestTblC(itemID varchar(30),descr varchar(50))goinsert into TestTblA values (getdate(),'TWMUA','(408)-555-1211')insert into TestTblA values (getdate(),'TWMUA','(408)-555-1212')insert into TestTblA values (getdate(),'TWMUB','(408)-555-1211')insert into TestTblA values (getdate(),'TWMUB','(408)-555-1212')insert into TestTblA values (getdate(),'TWMUB','(408)-555-1213')insert into TestTblA values (getdate(),'TWMUC','(408)-555-1211')insert into TestTblA values (getdate(),'TWMUC','(408)-555-1212')insert into TestTblA values (getdate(),'TWMUC','(408)-555-1213')insert into TestTblA values (getdate(),'WWEXI','(408)-555-1211')insert into TestTblA values (getdate(),'WWEXI','(408)-555-1212')insert into TestTblA values (getdate(),'WWEXI','(408)-555-1211')insert into TestTblB values ('TWMUA','1000-000043-000','Y')insert into TestTblB values ('TWMUB','1000-100002-001','Y')insert into TestTblB values ('TWMUC','1000-200005-000','Y')insert into TestTblB values ('WWEXI','1000-401001-000','Y')insert into TestTblB values ('WWEXI','1000-401002-000','Y')insert into TestTblC values ('1000-000043-000','descrUA')insert into TestTblC values ('1000-100002-001','descrUB')insert into TestTblC values ('1000-200005-000','descrUC')insert into TestTblC values ('1000-401001-000','descrWW')insert into TestTblC values ('1000-401002-000','descrWW')----------------Query follows------------SELECT A.ShipDate,A.CPEId,ItemId = CASEWHEN A.CPEId = 'TWMUA' THEN 'New - Single User'WHEN A.CPEID = 'TWMUB' THEN 'New - Multi User'WHEN A.CPEID = 'TWMUC' THEN 'New - Triple User'When B.ITEMID is NULL THEN 'Unknown'When B.ITEMID = ' ' THEN 'Unknown'else B.ItemIdend,MODEL_NO = CaseWhen B.ITEMID = '1000-000043-000' Then rtrim(C.DESCR)When B.ITEMID = '1000-100002-001' Then rtrim(C.DESCR)When B.ITEMID = '1000-200005-000' Then rtrim(C.DESCR)WHEN A.CPEId = 'TWMUA' THEN '1100'WHEN A.CPEID = 'TWMUB' THEN '1100'WHEN A.CPEID = 'TWMUC' THEN '1000SW'When C.DESCR is NULL THEN 'Unknown'else 'Unknown'end ,COUNT(A.phonenum)FROM TestTblA A LEFT OUTER JOIN TestTblB B ON A.CPEID=B.CPEID andb.active = 'Y'LEFT OUTER JOIN TestTblC C ON B.ItemId=C.ITEMIDGROUP BY A.ShipDate,A.CPEId,B.ItemId,C.DESCRORDER BY A.ShipDate,A.CPEId,B.ItemId,C.DESCR---- end of queryThe result (modified the output format to fit a single line)ShipDate CPEId ItemId MODEL_NO Count2003-07-18 TWMUA New - Single User descrUA 22003-07-18 TWMUB New - Multi User descrUB 32003-07-18 TWMUC New - Triple User descrUC 32003-07-18 WWEXI 1000-401001-000 NULL 32003-07-18 WWEXI 1000-401002-000 NULL 3** The problem **I need WWEXI or any similar entry to only show once, it shows twice.Thanks for your help.

View 3 Replies View Related







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