473,386 Members | 1,753 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

Trying to do a COUNT/AS RANK and it will not work.

Hello everyone! I am new to SQL and have given myself a 3 Day crash course! I apologize for my lack of knowledge. A project was assigned to me for work and so now I need to get it done.

I am running SQL SERVER 2008. I have one Database. It is called "HomeHealth". It has 3 Tables.

1.HomeCareAgencies (Holds the Agency Information such as name, address, phone, as well as an ID that is called Mnemonic in the table.
2.MoCounties (It holds, County Names, Services Offered and also has the Mnemonic field. This table is for 1 State.
3. ILCounties (Same as MoCounties but is for a second state.

Now, I need to be able to run a query that will give me all fields from HomeCareAgencies, MoCounties County Name and Services as well as ILCounties County Name and Services.
Seems like it would be easy and in fact I have accomplished this. However, It creates a result of about 9,000 rows because if one home Care Agency is in multiple counties in both states and offers multiple services it displays it in individual lines. I need it to have one line for the Agency to include all of the MoCounties, IlCounties and all services that it provides.

I tried using a Count(*)AS Rank in my query but it flakes out.

This Query works great:
________________________________________________
Expand|Select|Wrap|Line Numbers
  1. SELECT Services, County, 
  2.    COUNT(*) AS Rank
  3. FROM ILCounties AS IlCounties
  4.    INNER JOIN HomeCareAgencies AS HomeCareAgencies
  5.    ON ILCounties.Mnemonic = HomeCareAgencies.Mnemonic
  6.       AND ILCounties.Mnemonic  <= HomeCareAgencies.Mnemonic
  7. GROUP BY Services, 
  8.    County
__________________________________________________

However it doesn't include the Data from the HomeCareAgencies table.

I am sorry for the length of this. Any and ALL suggestions are extremely appreciated!! Thank you sincerely.
Feb 3 '13 #1
12 1739
NeoPa
32,556 Expert Mod 16PB
Although you have laid out your question very well Ken, especially for one who is new to the site, I'm not sure I follow it all too well.

What I do see though, is that you will probably need, as a start, a base query that has [HomeCareAgencies] on the left, with LEFT JOINs to both of the other two tables. Something like :
Expand|Select|Wrap|Line Numbers
  1. ...
  2. FROM   ([HomeCareAgencies]
  3.        LEFT JOIN
  4.        [ILCounties]
  5.   ON   HomeCareAgencies.Mnemonic=ILCounties.Mnemonic)
  6.        LEFT JOIN
  7.        [MOCounties]
  8.   ON   HomeCareAgencies.Mnemonic=MOCounties.Mnemonic
I would add that having your counties stored in two separate tables is unlikely to be Normalised (See Database Normalisation and Table Structures), and should probably (almost certainly) be avoided.

I'm guessing here, but if you have counties that belong in Missouri an Illinois then they should all be stored in the same table with a simple field that indicates which state they're from.

PS. The AS (or ALIAS) keyword is provided to give a shorthand version of an object. It makes little sense to rename it as itself.
Feb 4 '13 #2
Rabbit
12,516 Expert Mod 8TB
I second NeoPa's comment about normalization.

Also, I don't understand why you are asking about the count function when it sounds like you are only using count in attempt to solve a problem and is not the problem itself.

The problem, if I am reading correctly, is not the count function, but that you want to concatenate multiple rows. In SQL Server 2008 and up, you have access to XML functionality that can do this for you.

An example of this is:
Expand|Select|Wrap|Line Numbers
  1. select ', ' + someField
  2. from someTable
  3. for XML path('')
You can use that in a subquery to concatenate multiple rows into one.
Feb 4 '13 #3
@NeoPa and @Rabbit- Thank you both for your responses. I cant't combine the Counties tables because they are used in a different program independently. So that is one of the hurdles I have. I guess the main issue I am trying to resolve is, that if one of the Agencies provides 5 different services it list that agency 5 times. I need it to list the agency 1 time with all 5 services listed for that 1 agency. I think that is what @Rabbit is trying to tell me but like I said at the beginning I have only been using SQL for 3 days so not quite sure. Thank you all again for your assistance.
Feb 4 '13 #4
Rabbit
12,516 Expert Mod 8TB
Even if you can't normalize your data, you will still use the solution in my post.
Feb 4 '13 #5
@ Rabbit,

I now have this statement:

Expand|Select|Wrap|Line Numbers
  1. SELECT     HomeCareAgencies.*,ILCounties.County,ILCounties.Mnemonic,ILCounties.Services,MoCounties.County,
  2.  
  3.                      ((SELECT',' + Services
  4.                       FROM ILCounties AS ILC
  5.                       FOR XML PATH('')))AS ILServicesAndCounties
  6.  
  7.  
  8. FROM         HomeCareAgencies LEFT JOIN dbo.ILCounties ON HomeCareAgencies.Mnemonic = ILCounties.Mnemonic
  9.              LEFT Join MoCounties ON HomeCareAgencies.Mnemonic = MoCounties.Mnemonic
It works as stated, however it is still not quite right. If one agency has Five services and 4 counties where it provides that service it lists that Agency info 4 times. So I guess what you provided is what I was wanting but is there a way to make it not list duplicates?
For example:

Currently reports like this
NAME | County | Services
Agency1|County1|Service,Service,Service1,Service1, Service1

I would like for it to look like this
NAME | County | Services
Agency1|County1|Service,Service1

Does that make sense? Is that even possible?? Again thank you so much for your assistance.
Feb 4 '13 #6
Rabbit
12,516 Expert Mod 8TB
To remove duplicates, use the distinct clause in the subquery.

Your subquery requires a reference to the outer query to return only the records for a particular agency, otherwise you're going to get every service for every agency.

Also, you probably don't want to join to the county table because you will get duplicate rows.
Feb 4 '13 #7
@Rabbit YOU ARE A GENIUS!!
So here is the code I have got so far:
Expand|Select|Wrap|Line Numbers
  1. SELECT HomeCareAgencies.*,MoCounties.ServicesOffered,MoCounties.Mnemonic,
  2.                 ((SELECT DISTINCT County + ',' 
  3.                       FROM MoCounties AS MC
  4.                       WHERE MC.Mnemonic = HomeCareAgencies.Mnemonic
  5.                       FOR XML PATH('')))AS MoCounty
  6. FROM         [HomeCareAgencies],MoCounties
It displays one line with all Agency information and all the counties that it services in one field. Is it possible to have a subquery inside a subquery? I need to do this same thing for the services as well as the counties and services for the other state. I feel like this is getting REAL close to what I need. You are amazing!
Feb 4 '13 #8
Rabbit
12,516 Expert Mod 8TB
Yes, you can nest subqueries. I would suggest a union subquery in place of the table MoCounties.

I notice you still have MoCounties in your outer query. I though your goal was to have one row per agency? If that's what you want, you can't have MoCounties in your outer query.
Feb 4 '13 #9
NeoPa
32,556 Expert Mod 16PB
K3nSchr0eder:
@Rabbit YOU ARE A GENIUS!!
Not far off as it happens. His latest point is also worth considering carefully ;-)
Feb 4 '13 #10
Thank you both sooo much for your assistance. I have now got exactly what I wanted.
Here is the final query:
Expand|Select|Wrap|Line Numbers
  1. SELECT     HomeCareAgencies.*,
  2.            ((SELECT DISTINCT',' + Services 
  3.               FROM ILCounties 
  4.               WHERE HomeCareAgencies.Mnemonic = ILCounties.Mnemonic
  5.               FOR XML PATH('')))AS ILService,
  6.               ((SELECT DISTINCT ',' + County
  7.                 FROM ILCounties
  8.                 WHERE HomeCareAgencies.Mnemonic = ILCounties.Mnemonic
  9.                 FOR XML PATH(''))) AS ILCounties,
  10.                  ((SELECT DISTINCT ',' + Services
  11.                    FROM MoCounties
  12.                    WHERE HomeCareAgencies.Mnemonic = MoCounties.Mnemonic
  13.                    FOR XML PATH(''))) AS MoServices,
  14.                     ((SELECT DISTINCT ',' + County
  15.                       FROM MoCounties
  16.                       WHERE HomeCareAgencies.Mnemonic = MoCounties.Mnemonic
  17.                       FOR XML PATH(''))) AS MoCounties
  18.  
  19. FROM HomeCareAgencies 
Genius is an understatement for you both!
Feb 5 '13 #11
ck9663
2,878 Expert 2GB
Be careful, that looks like an RBAR.

From the looks of it, your requirement look like this

Good Luck, nevertheless!!!


~~ CK
Feb 5 '13 #12
NeoPa
32,556 Expert Mod 16PB
You may find RBAR: 'Row By Agonizing Row' helpful in order to understand where CK is going with that ;-)
Feb 5 '13 #13

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

Similar topics

7
by: Mark | last post by:
Hi - could anyone please tell me why this line: <td width="116" height="22" nowrap id="toptSearch" class="mtTabOnTop" onClick="changeLoc('fixit_proceduresresultstick.asp','search')">Search <img...
4
by: NH | last post by:
Hi, I just cannot get this to work. I want to make a cell editable in a datagrid only if the value of another cell is something specific. I am able to capture the value of the other cell via the...
1
by: Lal - Luxor | last post by:
please help me. how to work object.move will work on ve.net regards lal
2
by: Money | last post by:
When we do this Test *ptr=new Test; then runtime memory manager will allocate 10*sizeof(Test) + X bytes(X varying from implementation to implementation) But instead if I call operator new...
4
by: alice | last post by:
I'm trying to get sounds to play on image mouseovers using dreamweaver 8, and I found out that the code it generates to do this only works for IE. Is there a way to do this so that it will work...
2
by: Damfino | last post by:
Hi all, Newbie question here wrt defining a class that will work on bits read from a binary file. How would you go about doing it? As an example please look at the structure of my data given...
1
by: Bergamot | last post by:
marss wrote: You may be trying to fix the wrong problem. Post a URL, then maybe we'll see a better way to accomplish whatever your goal is. -- Berg
1
by: janiecarter | last post by:
Hi all, I have a query called and I want to rank each customer grouped on the field and then by descending order on . I have found many solutions where I can use a subquery to do this eg: ...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
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,...

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.