473,626 Members | 3,041 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Complicated query - select based on value

jqq
SQL2K on W2Kserver

I need some help revamping a rather complicated query. I've given the
table and existing query information below. (FYI, changing the
database structure is right out.)

The current query lists addresses with two particular types
('MN30D843J2', 'SC93JDL39D'). I need to change this to (1) check each
contact for address type 'AM39DK3KD9' and then (2) if the contact has
type 'AM39DK3KD9' select types ('AM39DK3KD9', 'ASKD943KDI') OR if the
contact does not have that type then select types ('MN30D843J2',
'SC93JDL39D'). (Context - the current query selects two standard
address types "Main" and "Secondary" ; we've added new data and now have
types "Alternate Main" and "Alternate Secondary". If the Contact has
Alternate addresses, I need to select those; if not, I need to select
the standard addresses. There are other address types in use, so I
must specify which types to select.)

Can anyone point me in the right direction?

Thanks very much! jamileh

CREATE TABLE [CONTACTS] (
[CONTACT_X] [char] (10),
[LONGNAME] [char] (75),
[ACTIVE] [bit])

CREATE TABLE [CONTACTADDRESSE S] (
[CONTACT_X] [char] (10),
[ADDRESS_X] [char] (10),
[ADDRESSTYPE_REF X] [char] (10),
[ACTIVE] [bit])

CREATE TABLE [ADDRESSES] (
[ADDRESS_X] [char] (10),
[ADDRESSLINE1] [char] (60),
[ADDRESSLINE2] [char] (60),
[CITY] [char] (20),
[STATE] [char] (2),
[ZIPCODE] [char] (11),
[PHONE] [char] (10))

CREATE TABLE [REFERENCETABLE] (
[REFERENCETABLE_ X] [char] (10),
[ADDRESS_X] [char] (10),
[DESCRIPTION] [char] (60))

CREATE TABLE [MASTERTABLE] (
[CONTACT_X] [char] (10),
[RECORDTYPE] [char] (1),
[ACTIVE] [bit])

CREATE VIEW vw_CONTACTInfo_ ListLoc
AS
SELECT CONTACTS.CONTAC T_X, CONTACTS.LONGNA ME,
CONTACTADDRESSE S.ADDRESSTYPE_R EFX,
Type_REFERENCET ABLE.DESCRIPTIO N AS Type_DESCRIPTIO N,
CONTACTADDRESSE S.ADDRESS_X, ADDRESSES.ADDRE SSLINE1,
ADDRESSES.ADDRE SSLINE2, ADDRESSES.CITY, ADDRESSES.STATE ,
ADDRESSES.ZIPCO DE, ADDRESSES.PHONE
FROM CONTACTS INNER JOIN CONTACTADDRESSE S ON
CONTACTS.CONTAC T_X = CONTACTADDRESSE S.CONTACT_X INNER JOIN
ADDRESSES ON CONTACTADDRESSE S.ADDRESS_X =
ADDRESSES.ADDRE SS_X
INNER JOIN REFERENCETABLE Type_REFERENCET ABLE ON
CONTACTADDRESSE S.ADDRESSTYPE_R EFX =
Type_REFERENCET ABLE.REFERENCET ABLE_X
WHERE (CONTACTS.ACTIV E = 1) AND (CONTACTADDRESS ES.ADDRESSTYPE_ REFX
IN
('MN30D843J2', 'SC93JDL39D') AND (CONTACTADDRESS ES.ACTIVE =
1)) AND
(CONTACTS.CONTA CT_X IN
(SELECT CONTACT_X FROM MASTERTABLE WHERE
ACTIVE = 1 AND RECORDTYPE = 'E'))

Jul 23 '05 #1
10 2447

"jqq" <jq*@myrealbox. com> wrote in message
news:11******** *************@f 14g2000cwb.goog legroups.com...
SQL2K on W2Kserver

I need some help revamping a rather complicated query. I've given the
table and existing query information below. (FYI, changing the
database structure is right out.)

The current query lists addresses with two particular types
('MN30D843J2', 'SC93JDL39D'). I need to change this to (1) check each
contact for address type 'AM39DK3KD9' and then (2) if the contact has
type 'AM39DK3KD9' select types ('AM39DK3KD9', 'ASKD943KDI') OR if the
contact does not have that type then select types ('MN30D843J2',
'SC93JDL39D'). (Context - the current query selects two standard
address types "Main" and "Secondary" ; we've added new data and now have
types "Alternate Main" and "Alternate Secondary". If the Contact has
Alternate addresses, I need to select those; if not, I need to select
the standard addresses. There are other address types in use, so I
must specify which types to select.)

Can anyone point me in the right direction?

Thanks very much! jamileh


<snip>

The short answer is probably to see CASE in Books Online. If you need more
information, I suggest you provide some INSERT statements for sample data,
and also the output you expect - it's not very clear (to me) exactly what
your query should return.

http://www.aspfaq.com/etiquette.asp?id=5006

Simon
Jul 23 '05 #2
AK
If the Contact has (INNER JOIN)
Alternate addresses, I need to select those;

UNION ALL
if not, NOT EXISTS(....)

I need to select
the standard addresses.

Jul 23 '05 #3
Without better specs, this is hard. The tables had no keys; the names
of the data elements are awful, you even put physical storage and usage
into the names! You are using bit flags in SQL. There does not seem to
be any consistent design here. Clraning it up a bit, I got this:

CREATE TABLE Contacts
(contact_id CHAR(10) NOT NULL PRIMARY KEY,
long_name CHAR(75) NOT NULL);

CREATE TABLE Addresses
(address_id CHAR(10) NOT NULL PRIMARY KEY,
address_line1 CHAR(35) NOT NULL, -- usps lengths
address_line2 CHAR(35) NOT NULL,
city_name CHAR(20) NOT NULL,
state_code CHAR(2) NOT NULL,
zip_code CHAR(9) NOT NULL,
phone_nbr CHAR(10) NOT NULL));

Your codes belong to the relationship, and not in their own tables,
something more like this

CREATE TABLE ContactAddresse s
(contact_id CHAR(10) NOT NULL
REFERENCES Contacts (contact_id)
ON DELETE CASCADE
ON UPDATE CASCADE,
address_id CHAR(10) NOT NULL
REFERENCES Addresses (address_id)
ON DELETE CASCADE
ON UPDATE CASCADE,
address_type INTEGER NOT NULL, -- see suggestion below
PRIMARY KEY (contact_id, address_id, address_type)
contact_status CHAR(3) DEFAULT 'act' NOT NULL
CHECK (contact_status IN ('act', 'old', ..));

Views should be kept simple so they can be used in many place. And
unless they dela wiyth a Volkswagen, you do not prefix them with "vw_"
:)

CREATE VIEW ContactInfo (contact_id, long_name,
address_type, address_id,
address_line1, address_line2,
city_name, state_code, zip_code,
phone_nbr)
AS
SELECT C.contact_id, C.long_name,
CA.address_type , CA.address_id,
A.address_line1 , A.address_line2 ,
A.city_name, A.state_code, A.zip_code,
A.phone_nbr
FROM Contacts AS C,
ContactAddresse s AS CA,
Addresses AS A
WHERE CA.contact_id = C.contact_id
AND CA.address_id = A.address_id
AND CA.address_type BETWEEN 100 AND 299;
the current query selects two standard address types "Main" and "Secondary" ; we've added new data and now have types "Alternate Main" and "Alternate Secondary". If the Contact has Alternate addresses, I need to select those; if not, I need to select the standard addresses. <<


You need a better encoding scheme than those awful ten-letter
nightmares. I read your narrative as meaning one contact can have only
one address of each type. Here is a hierarchical encoding suggestion,
with some room for growth.

100-199 = Main Address
110-119 = Alternative Main Address
200-299 = Secondary Address
210-219 = Alternative Secondary Address

The query would be something like this:

SELECT DISTINCT I1.*
FROM ContactInfo AS I1
WHERE address_type IN (200, 210) -- has secondary address
OR (address_type IN (100, 110) -- has main address
AND NOT EXISTS
(SELECT *
FROM ContactInfo AS I2
WHERE address_type IN (200, 210) -- no secondary address
AND I1.contact_id = I2.contact_id
AND I1.address_id = I2.address_id)) ;

Jul 23 '05 #4
jqq
My apologies for leaving out the data, I didn't want to get too long in
my original post if it wasn't needed. Please see below (including one
fix on a table).

So, the current query will pull John Smith's "standard" addresses on
Main, Second, and Third streets, plus Frank Doe's "standard" addresses
on Main, Second and Third streets.

The results I need would give John Smith's "standard" addresses on
Main, Second, and Third streets, plus Frank Doe's "alternate" addresses
on Fifth and Sixth streets.

I've used CASE, but not to select multiple records based on one field.
I'm not sure how to make that work and I can't find anything in BOL to
explain it.

Thanks.
ALTER TABLE [REFERENCETABLE] DROP COLUMN [ADDRESS_X]

INSERT [CONTACTS] VALUES ('A1','John Smith',1)
INSERT [CONTACTS] VALUES ('B2','Frank Doe',1)
INSERT [CONTACTS] VALUES ('C3','Jane Jones',1)
INSERT [CONTACTS] VALUES ('D4','Susan Roe',0)
INSERT [CONTACTS] VALUES ('E5','George Brown',1)

INSERT [CONTACTADDRESSE S] VALUES ('A1','F1','MN3 0D843J2',1)
INSERT [CONTACTADDRESSE S] VALUES ('A1','G2','SC9 3JDL39D',1)
INSERT [CONTACTADDRESSE S] VALUES ('A1','H3','SC9 3JDL39D',1)
INSERT [CONTACTADDRESSE S] VALUES ('A1','I4','BL2 309DD3L',1)
INSERT [CONTACTADDRESSE S] VALUES ('A1','J5','AM3 9DK3KD9',0)
INSERT [CONTACTADDRESSE S] VALUES ('B2','K6','MN3 0D843J2',1)
INSERT [CONTACTADDRESSE S] VALUES ('B2','L7','SC9 3JDL39D',1)
INSERT [CONTACTADDRESSE S] VALUES ('B2','M8','SC9 3JDL39D',1)
INSERT [CONTACTADDRESSE S] VALUES ('B2','N9','BL2 309DD3L',1)
INSERT [CONTACTADDRESSE S] VALUES ('B2','O0','AM3 9DK3KD9',1)
INSERT [CONTACTADDRESSE S] VALUES ('B2','P1','ASK D943KDI',1)
INSERT [CONTACTADDRESSE S] VALUES ('C3','Q2','AM3 9DK3KD9',1)
INSERT [CONTACTADDRESSE S] VALUES ('D4','R3','AM3 9DK3KD9',1)
INSERT [CONTACTADDRESSE S] VALUES ('E5','S4','AM3 9DK3KD9',1)

INSERT [ADDRESSES] VALUES ('F1','123 Main
St','','Anytown ','PA','12345', '5074951548')
INSERT [ADDRESSES] VALUES ('G2','456 Second St','Apt
9','Anytown','P A','45678','507 4328548')
INSERT [ADDRESSES] VALUES ('H3','789 Third
St','','Anytown ','PA','45678', '5074321111')
INSERT [ADDRESSES] VALUES ('I4','987 Fourth
St','','Anytown ','PA','12345', '5074959999')
INSERT [ADDRESSES] VALUES ('J5','654 Fifth
St','','Anytown ','PA','12345', '5074955555')
INSERT [ADDRESSES] VALUES ('K6','1 Main
St','','Somewhe re','UT','87654 ','2426831234')
INSERT [ADDRESSES] VALUES ('L7','2 Second St','Suite
600','Somewhere ','UT','87654', '2426835678')
INSERT [ADDRESSES] VALUES ('M8','3 Third
St','','Somewhe re','UT','87654 ','2426839876')
INSERT [ADDRESSES] VALUES ('N9','4 Fourth
St','','Somewhe re','UT','87654 ','2426835432')
INSERT [ADDRESSES] VALUES ('O0','5 Fifth
St','','Somewhe re','UT','87654 ','2426831111')
INSERT [ADDRESSES] VALUES ('P1','6 Sixth
St','','Somewhe re','UT','87654 ','2426839999')
INSERT [ADDRESSES] VALUES ('Q2','123 NoGood
St','','Nowhere ','AK','98765', '9051875135')
INSERT [ADDRESSES] VALUES ('R3','456 NotMe
St','','Nonesuc h','CA','43210' ,'7631584625')
INSERT [ADDRESSES] VALUES ('S4','789 UhOh
St','','Noway', 'GA','36847','6 427892462')

INSERT [REFERENCETABLE] VALUES ('MN30D843J2',' Standard Main')
INSERT [REFERENCETABLE] VALUES ('SC93JDL39D',' Standard Secondary')
INSERT [REFERENCETABLE] VALUES ('AM39DK3KD9',' Alternate Main')
INSERT [REFERENCETABLE] VALUES ('ASKD943KDI',' Alternate Secondary')
INSERT [REFERENCETABLE] VALUES ('BL2309DD3L',' Billing Only')

INSERT [MASTERTABLE] VALUES ('A1','E',1)
INSERT [MASTERTABLE] VALUES ('B2','E',1)
INSERT [MASTERTABLE] VALUES ('C3','N',1)
INSERT [MASTERTABLE] VALUES ('D4','E',1)
INSERT [MASTERTABLE] VALUES ('E5','E',0)

Jul 23 '05 #5
jqq
As I said, changing the database structure is right out. I didn't
build the beastie - it's the backend for a proprietary application.
The only thing I can do is pull data.

These views are for the exact purpose of selecting very specific sets
of data to provide to some websites. This one's not half bad, you
should see some of the others!

I did leave out PKs, etc. - sorry. The tables are actually much
bigger & I was trying to just pull the needed info for simplicity. If
there's something specific that would help, please let me know & I'll
post an update. In general, you're right and the "tablename_ K" columns
are PKs and FKs.

As you can see in my last post (with data), one contact can have
multiple addresses of each type and I need to pull all addresses of the
correct types.

Any rate, thanks for the advice! j

p.s. What's wrong with bit flags?

Jul 23 '05 #6
jqq
I read this several times without any clue what you meant, but I think
it's beginning to permeate into my poor, bleeding braincells. I'll see
what I can come up with. Thanks!

Jul 23 '05 #7
jqq (jq*@myrealbox. com) writes:
p.s. What's wrong with bit flags?


Nothing.
--
Erland Sommarskog, SQL Server MVP, es****@sommarsk og.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp
Jul 23 '05 #8
jqq (jq*@myrealbox. com) writes:
My apologies for leaving out the data, I didn't want to get too long in
my original post if it wasn't needed. Please see below (including one
fix on a table).

So, the current query will pull John Smith's "standard" addresses on
Main, Second, and Third streets, plus Frank Doe's "standard" addresses
on Main, Second and Third streets.

The results I need would give John Smith's "standard" addresses on
Main, Second, and Third streets, plus Frank Doe's "alternate" addresses
on Fifth and Sixth streets.


This query gives the result described above, but does not match your
description in the first post. But maybe you simply messed up on all
these terrible 10-letter codes when you composed the sample data.

SELECT C.CONTACT_X, C.LONGNAME, CA.ADDRESSTYPE_ REFX,
R.DESCRIPTION AS Type_DESCRIPTIO N, CA.ADDRESS_X,
A.ADDRESSLINE1, A.ADDRESSLINE2, A.CITY, A.STATE, A.ZIPCODE,
A.PHONE
FROM CONTACTS C
JOIN CONTACTADDRESSE S CA ON C.CONTACT_X = CA.CONTACT_X
JOIN ADDRESSES A ON CA.ADDRESS_X = A.ADDRESS_X
JOIN REFERENCETABLE R ON CA.ADDRESSTYPE_ REFX = R.REFERENCETABL E_X
WHERE C.ACTIVE = 1
AND CA.ADDRESSTYPE_ REFX IN ('MN30D843J2', 'SC93JDL39D')
AND CA.ACTIVE = 1
AND C.CONTACT_X IN (SELECT M.CONTACT_X
FROM MASTERTABLE M
WHERE M.ACTIVE = 1
AND M.RECORDTYPE = 'E')
AND NOT EXISTS (SELECT *
FROM CONTACTADDRESSE S CA1
WHERE C.CONTACT_X = CA1.CONTACT_X
AND CA1.ADDRESSTYPE _REFX IN ('ASKD943KDI'))
UNION ALL
SELECT C.CONTACT_X, C.LONGNAME, CA.ADDRESSTYPE_ REFX,
R.DESCRIPTION AS Type_DESCRIPTIO N, CA.ADDRESS_X,
A.ADDRESSLINE1, A.ADDRESSLINE2, A.CITY, A.STATE, A.ZIPCODE,
A.PHONE
FROM CONTACTS C
JOIN CONTACTADDRESSE S CA ON C.CONTACT_X = CA.CONTACT_X
JOIN ADDRESSES A ON CA.ADDRESS_X = A.ADDRESS_X
JOIN REFERENCETABLE R ON CA.ADDRESSTYPE_ REFX = R.REFERENCETABL E_X
WHERE C.ACTIVE = 1
AND CA.ADDRESSTYPE_ REFX IN ('AM39DK3KD9', 'ASKD943KDI')
AND CA.ACTIVE = 1
AND C.CONTACT_X IN (SELECT M.CONTACT_X
FROM MASTERTABLE M
WHERE M.ACTIVE = 1
AND M.RECORDTYPE = 'E')

--
Erland Sommarskog, SQL Server MVP, es****@sommarsk og.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp
Jul 23 '05 #9
They are a proprietary, low level data type. The design is the way we
handled things with punch cards in the old days. Flags are usually
computed columns. It is usually better to invent a status code which
can be extended, or to capture the date of an event, etc.

Jul 23 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
5682
by: JDJones | last post by:
Using PHP and MySQL. Trying to put a list of categories into a drop down select option of a form like: <form name="form" action="<? print $_SERVER?>" method="get"> <select name="subject"> <option value=""></option> <option value="field1">Field 1</option> <option value="field2">Field 2</option> </select>
20
10130
by: | last post by:
If I need to check if a certain value does exist in a field, and return either "yes" or "not" which query would be the most effestive?
4
2652
by: Orion | last post by:
Hi, This is kind of last minute, I have a day and a half left to figure this out. I'm working on a project using ms-sqlserver. We are creating a ticket sales system, as part of the system, I need to be able to do a search for specific tickets withing price ranges, different locations within the theaters, etc. etc. My problem is in the search one of the criteria is to search for a group of seats together. For example let's say...
2
2536
by: Willem | last post by:
Hi there, I'm sort of new with doing much record manipulation with queries. Up till now I've been programming VBA and doing record looping to get my results. This works fine but tends to get very, very slow as the number of records grows - somewhere in the number of 5,000,000. I imagine queries are much faster but am not quite sure if queries will do the trick. My problem:
2
2912
by: neptune | last post by:
I have a query where each customer has an or . Sometimes both fields for a customer are populated, but if is null, then will be populated and vice versa. I have a form, , where I select a value for from a combo box. In my query I set the criteria for to ... My query finds the proper values for . Now I also want to find the values if I select a value for in a separate combo box. In both controls, OnChange, I set the value of
3
579
by: John young | last post by:
I have been looking for an answer to a problem and have found this group and hope you can assist . I have been re doing a data base I have made for a car club I am with and have been trying to make a query that selects from a table as desribed below .. I have a table (Volunteer) that has a member field (memnumber) and a number of fields that are headed in various categories and are yes/no formated
26
2159
by: Jeff | last post by:
Ok gang. Here is something complicated, well, at least to me anyway. Using Access DB I have a table in my DB called members. In that table, I have 2 tables I will be using "username" and "points" Now, I also have a table called all_matches. This table contains every match report. Over 25,000 of them. I have a "username" field an "outcome" field an "username1" field and "extra_match" field.
2
3229
by: Joe C. | last post by:
hello, just joined the group, i've run into a wall and am seeking some help. here is my query: SELECT DATEPART(year, TTmain.TTDate) AS 'Year', SUM(TTmain.TTAmt) + SUM(TTmain.TTFee) AS 'Total' FROM TTmain INNER JOIN TTdealers ON
4
4572
by: zion4ever | last post by:
Hello good people, Please bear with me as this is my first post and I am relative new to ASP. I do have VB6 experience. I have a form which enables users within our company to do an intranet reservation of available resources (laptops, beamers, etc). The MySql database queries are already in place, as is the ASP administration panel. The frontend that users will see however, still needs some work. I'm really close, but since I'm no...
0
8192
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8696
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...
1
8358
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
8502
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
7188
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...
1
6119
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4090
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4195
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2621
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

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.