473,796 Members | 2,426 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Query to reduce a 1-to-n relationship to 1-to-1

4 New Member
My problem is as follows:
I have a customer table and an address table. A customer can have 0, 1 or many addresses. The query result I'm trying to get produces 1 and only 1 row for each customer, with either 1 address or null's for the appropriate address fields. Here's some simple sql to demonstrate:

create table test_customer (custid char(10), custname char(20))
create table test_address (custid char(10), addrid char(10), city char(20))

insert into test_customer values ('ID1', 'Cust1')
insert into test_customer values ('ID2', 'Cust2')
insert into test_customer values ('ID3', 'Cust3')
insert into test_customer values ('ID4', 'Cust4')

insert into test_address values ('ID1', 'Addr1a', 'Paris')
insert into test_address values ('ID1', 'Addr1b', 'London')
insert into test_address values ('ID2', 'Addr2a', 'New York')
insert into test_address values ('ID3', 'Addr3a', 'Tokyo')

select a.custid, a.custname, b.addrid, b.city
from test_customer a, test_address b
where a.custid *= b.custid

The select produces this result:
ID1 Cust1 Addr1a Paris
ID1 Cust1 Addr1b London
ID2 Cust2 Addr2a New York
ID3 Cust3 Addr3a Tokyo
ID4 Cust4 NULL NULL

The result I'm trying to achieve is:
ID1 Cust1 Addr1a Paris
ID2 Cust2 Addr2a New York
ID3 Cust3 Addr3a Tokyo
ID4 Cust4 NULL NULL

When I try to do a subquery to produce the 1-1 customer/address join, and then do an outer query to add the city, I get the infamous "not permitted outer join" error message:

select a.custid, a.custname, b.addrid, b.city
from test_customer a, test_address b,
(select c.custid, min(d.addrid) sub1addr
from test_customer c, test_address d
where c.custid *= d.custid
group by c.custid) as sub1
where a.custid *= b.custid
and a.custid *= sub1.custid
and b.addrid *= sub1.sub1addr

Output:
Server: Msg 301, Level 16, State 1, Line 1
Query contains an outer-join request that is not permitted.

The subtle change of trying to make the last line an inner join gives me this error:
select a.custid, a.custname, b.addrid, b.city
from test_customer a, test_address b,
(select c.custid, min(d.addrid) sub1addr
from test_customer c, test_address d
where c.custid *= d.custid
group by c.custid) as sub1
where a.custid *= b.custid
and a.custid *= sub1.custid
and b.addrid = sub1.sub1addr

Server: Msg 303, Level 16, State 1, Line 1
The table 'test_address' is an inner member of an outer-join clause. This is not allowed if the table also participates in a regular join clause.

Thanks for any suggestions. Suggestions such as changing the design aren't feasible, as this is a simplified version of a db that's in production.
Aug 24 '07 #1
4 2218
Jim Doherty
897 Recognized Expert Contributor
My problem is as follows:
I have a customer table and an address table. A customer can have 0, 1 or many addresses. The query result I'm trying to get produces 1 and only 1 row for each customer, with either 1 address or null's for the appropriate address fields. Here's some simple sql to demonstrate:

create table test_customer (custid char(10), custname char(20))
create table test_address (custid char(10), addrid char(10), city char(20))

insert into test_customer values ('ID1', 'Cust1')
insert into test_customer values ('ID2', 'Cust2')
insert into test_customer values ('ID3', 'Cust3')
insert into test_customer values ('ID4', 'Cust4')

insert into test_address values ('ID1', 'Addr1a', 'Paris')
insert into test_address values ('ID1', 'Addr1b', 'London')
insert into test_address values ('ID2', 'Addr2a', 'New York')
insert into test_address values ('ID3', 'Addr3a', 'Tokyo')

select a.custid, a.custname, b.addrid, b.city
from test_customer a, test_address b
where a.custid *= b.custid

The select produces this result:
ID1 Cust1 Addr1a Paris
ID1 Cust1 Addr1b London
ID2 Cust2 Addr2a New York
ID3 Cust3 Addr3a Tokyo
ID4 Cust4 NULL NULL

The result I'm trying to achieve is:
ID1 Cust1 Addr1a Paris
ID2 Cust2 Addr2a New York
ID3 Cust3 Addr3a Tokyo
ID4 Cust4 NULL NULL

When I try to do a subquery to produce the 1-1 customer/address join, and then do an outer query to add the city, I get the infamous "not permitted outer join" error message:

select a.custid, a.custname, b.addrid, b.city
from test_customer a, test_address b,
(select c.custid, min(d.addrid) sub1addr
from test_customer c, test_address d
where c.custid *= d.custid
group by c.custid) as sub1
where a.custid *= b.custid
and a.custid *= sub1.custid
and b.addrid *= sub1.sub1addr

Output:
Server: Msg 301, Level 16, State 1, Line 1
Query contains an outer-join request that is not permitted.

The subtle change of trying to make the last line an inner join gives me this error:
select a.custid, a.custname, b.addrid, b.city
from test_customer a, test_address b,
(select c.custid, min(d.addrid) sub1addr
from test_customer c, test_address d
where c.custid *= d.custid
group by c.custid) as sub1
where a.custid *= b.custid
and a.custid *= sub1.custid
and b.addrid = sub1.sub1addr

Server: Msg 303, Level 16, State 1, Line 1
The table 'test_address' is an inner member of an outer-join clause. This is not allowed if the table also participates in a regular join clause.

Thanks for any suggestions. Suggestions such as changing the design aren't feasible, as this is a simplified version of a db that's in production.

Ok no design change so lets go with what we have here well from what I can see its a question of returning the ONE address for each customer even if they have no address... I've utilised a standard UDF function for that to return a concatenated single return value for the address which you can always parse out to extra columns once you see the return dataset in analyser or opening the view. Here is the script pasted below to create the view and the UDF

--Try this for good measure the UDF function returns the top 1 address
--for the CustID passed in we then SELECT out using the view after that
--the view produces a column of the concatenated address fields essentialthe
--requirements of the single return value the UDF demands
--you can then parse out the elements of the concatenation to extra columns
--I did not know your needs on that so I'll leave that one with you

CREATE FUNCTION UDF_CustomerAdd ress
( @CustID char(10) )
RETURNS varchar(255)
AS
BEGIN
RETURN (
SELECT TOP 1
COALESCE (LTRIM(RTRIM(Ad drid)), '')+' '+ COALESCE (LTRIM(RTRIM(Ci ty)), '') as address
FROM test_Address
WHERE CustID = @CustID)
END
Go

CREATE VIEW dbo.vw_Customer sSingleAddress
AS
SELECT custid, custname, dbo.UDF_Custome rAddress(custid ) AS [Customer Address]
FROM dbo.test_custom er
GO
Aug 24 '07 #2
bugs2bugs
4 New Member
Thanks Jim. This works, although I was hoping that the answer wouldn't involve having to parse the string returned by the function (I need to have these values available for loading into another table). Any other ideas out there?

Ok no design change so lets go with what we have here well from what I can see its a question of returning the ONE address for each customer even if they have no address... I've utilised a standard UDF function for that to return a concatenated single return value for the address which you can always parse out to extra columns once you see the return dataset in analyser or opening the view. Here is the script pasted below to create the view and the UDF

--Try this for good measure the UDF function returns the top 1 address
--for the CustID passed in we then SELECT out using the view after that
--the view produces a column of the concatenated address fields essentialthe
--requirements of the single return value the UDF demands
--you can then parse out the elements of the concatenation to extra columns
--I did not know your needs on that so I'll leave that one with you

CREATE FUNCTION UDF_CustomerAdd ress
( @CustID char(10) )
RETURNS varchar(255)
AS
BEGIN
RETURN (
SELECT TOP 1
COALESCE (LTRIM(RTRIM(Ad drid)), '')+' '+ COALESCE (LTRIM(RTRIM(Ci ty)), '') as address
FROM test_Address
WHERE CustID = @CustID)
END
Go

CREATE VIEW dbo.vw_Customer sSingleAddress
AS
SELECT custid, custname, dbo.UDF_Custome rAddress(custid ) AS [Customer Address]
FROM dbo.test_custom er
GO
Aug 24 '07 #3
azimmer
200 Recognized Expert New Member
Thanks Jim. This works, although I was hoping that the answer wouldn't involve having to parse the string returned by the function (I need to have these values available for loading into another table). Any other ideas out there?
How 'bout this one?
Expand|Select|Wrap|Line Numbers
  1. select t.custid, t.custname, addr.addrid, addr.city
  2. from
  3. (
  4. select a.custid, a.custname, min(b.addrid) as minaddrid
  5. from test_customer a left outer join test_address b on a.custid = b.custid
  6. group by a.custid, a.custname
  7. ) as t left outer join test_address addr on t.minaddrid=addr.addrid
  8.  
NB: Do not use the WHERE syntax for outer joins -- MSSQL hates it...
Aug 25 '07 #4
bugs2bugs
4 New Member
How 'bout this one?
Expand|Select|Wrap|Line Numbers
  1. select t.custid, t.custname, addr.addrid, addr.city
  2. from
  3. (
  4. select a.custid, a.custname, min(b.addrid) as minaddrid
  5. from test_customer a left outer join test_address b on a.custid = b.custid
  6. group by a.custid, a.custname
  7. ) as t left outer join test_address addr on t.minaddrid=addr.addrid
  8.  
NB: Do not use the WHERE syntax for outer joins -- MSSQL hates it...
Thanks, this is a MUCH more workable solution!
Aug 27 '07 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

226
12718
by: Stephen C. Waterbury | last post by:
This seems like it ought to work, according to the description of reduce(), but it doesn't. Is this a bug, or am I missing something? Python 2.3.2 (#1, Oct 20 2003, 01:04:35) on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> d1 = {'a':1} >>> d2 = {'b':2} >>> d3 = {'c':3}
8
7439
by: Andante.in.Blue | last post by:
Hello, I have just inherited a legacy Access 97 database. While going through it, I noticed something strange... its Relationships window (the one accessed by Tools --> Relationships) is almost empty. Now, as I ponder how a relation database could work without any relationships, I noticed that the queries of the database defined some relationships between the source tables and queries. Which leads me to the question, what is the...
1
20805
by: KLAU | last post by:
I have a field that retrieves information from an expression in a query. I have used a DLookup function to get the calculated field from the query. However, the relationship is 1-to-many so one site could have many units. How do I have the DLookUp field value change to a newly calcuated field when I navigate through the units? please see example below: On the Form: A site can have many units.
0
1865
by: leavandor | last post by:
I am trying to design a query that works with a relationship between a Table and a Query. I am comparing a value in the table with a computed value inside the query. The reason for this is that the Query calculates a field to become identical to the corresponding table field, for instance: Table 1 contains field "ID", which is WV008A00 Table 2 contains field "ID In", which is WV001000
5
1429
by: MattPF | last post by:
I have a table that is -- 30 Megabytes 90,000 rows ~65 columns My query goes SELECT city FROM table WHERE zip = 90210; It will then find about 10 matching records.
2
1801
by: Eckhart | last post by:
Dear All, Plz help me in optimising the following query, Reduce repeatable reads from the table via select ,ythe table sare not having referntial integrity constarints ,relations CREATE proc Rolex136Sync as DECLARE @date varchar(50),@ydate varchar(50) print CONVERT(char(11),(GETDATE()-1),100) SET @date =...
1
1282
by: crazdandconfusd | last post by:
I have a database with two tables I use for shipping information. One is for if I'm only shipping one item and the other is for a back page of a report for when I ship multiple items. If I'm shipping multiple items, I put SEE REVERSE in the single item block and then enter the rest in a subform linked to the multiple item table. I'm trying to generate a report that lists all items shipped using a tracking number, but when I create a query, I...
5
2884
by: themastertaylor | last post by:
I've got a system to manage various quotes for building materials for a number of sites. i want a query to produce a report that shows me who HASN'T quoted for which sites. basically so i can print it off and ring round and hurry them up a bit. I have my quote table which has the supplier ID, Site ID and an ID for each quote.(I enter each quote and specify which supplier and site it relates to. I've tried an unmatched query but can't...
16
27094
by: BNW | last post by:
I need help in finding out why I am not getting any data in my query. When I select all the fields in one table in my query grid and run it, the data is there. However, when I try to do it using to related tables and pull fields from both table in my query rid and run the query, data from both related tables are not showing in my query datasheet. What is the problem? The relationship line in my query is showing that the table are linked....
2
1274
mreed72
by: mreed72 | last post by:
I have a problem and can't get clear enough to figure it out. 2 tables in my database are related to each other. table1 = contacts table2 = Jobs both are a 1to1 relation, using the standard ID fields to relate to. now, each contact holds 1 specific job. Each contact has information associated with it. and it's related to the appropriate job (table2)
0
9680
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10456
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10230
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10174
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10012
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9052
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6788
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4118
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2926
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.