Solved

help with SQL

Posted on 2015-01-09
15
126 Views
Last Modified: 2015-01-09
I have two tables; a house table and a bed table.    The house table has a long value that is the number of total beds in the house.  The bed table has record for each bed that included a description, type, etc., and a status that indicates if the bed is vacant or occupied.  What I'm trying to do in one query is return all houses that have at least 1 open bed, with columns for total beds, occupied beds and vacant beds.  I don't know how to combine the JOIN with one or more aggregate functions that give a count of bed records with a status of vacant and/or occupied, or one aggregate function that give the number of vacant beds along with a calculation of: occupied bed = total beds - vacant beds.

Thanks
0
Comment
Question by:HLRosenberger
  • 8
  • 5
  • 2
15 Comments
 
LVL 24

Expert Comment

by:Phillip Burton
ID: 40540328
Can you post the structure of your tables please.
0
 
LVL 1

Author Comment

by:HLRosenberger
ID: 40540354
here ya go:

 

housetable.pngbedtable.png
0
 
LVL 1

Author Comment

by:HLRosenberger
ID: 40540356
bedtable.png
0
Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

 
LVL 24

Expert Comment

by:Phillip Burton
ID: 40540371
Something like:

with myTable as (
Select H.ID, 
(Select Count(*) from dbo.resource_home_bed as T where H.ID=T.FK_resource_home and T.FK_bed_status = "Open") as OpenBeds
from dbo.resource_home H
)
Select * from MyTable
Where OpenBeds>=1

Open in new window

0
 
LVL 1

Author Comment

by:HLRosenberger
ID: 40540396
Thanks.  I also need the number_of_beds from the home table.  I'm unfamiliar with the WITH syntax.
0
 
LVL 24

Expert Comment

by:Phillip Burton
ID: 40540405
with myTable as (
Select H.ID, sum(H.number_of_beds) as number_of_beds, 
(Select Count(*) from dbo.resource_home_bed as T where H.ID=T.FK_resource_home and T.FK_bed_status = "Open") as OpenBeds
from dbo.resource_home H
)
Select * from MyTable
Where OpenBeds>=1

Open in new window

0
 
LVL 24

Expert Comment

by:Phillip Burton
ID: 40540406
I'm assuming you are using SQL Server.
0
 
LVL 1

Author Comment

by:HLRosenberger
ID: 40540417
Ah, like this, right.

with myTable as (
Select H.ID,
(Select Count(*) from dbo.resource_home_bed as T where H.ID=T.FK_resource_home and T.FK_bed_status = "Open") as OpenBeds, H.number_of_beds
from dbo.resource_home H
)
Select * from MyTable
Where OpenBeds>=1
0
 
LVL 1

Author Comment

by:HLRosenberger
ID: 40540418
How do I subtract OPenBeds from Total beds to give a column names occupied beds?
0
 
LVL 24

Accepted Solution

by:
Phillip Burton earned 500 total points
ID: 40540426
Do it in the last two lines

with myTable as (
Select H.ID, sum(H.number_of_beds) as number_of_beds, 
(Select Count(*) from dbo.resource_home_bed as T where H.ID=T.FK_resource_home and T.FK_bed_status = "Open") as OpenBeds
from dbo.resource_home H
)
Select *,  number_of_beds - OpenBeds as OccupiedBeds 
from MyTable
Where OpenBeds>=1

Open in new window

0
 
LVL 1

Author Comment

by:HLRosenberger
ID: 40540431
I got this to work; is there a better way without having the Subquery clause specified twice?

with myTable as (
Select H.ID,
h.number_of_beds, (Select Count(*) from dbo.resource_home_bed as T where H.ID=T.FK_resource_home and T.FK_bed_status = 2) as OpenBeds,
  (h.number_of_beds - (Select Count(*) from dbo.resource_home_bed as T where H.ID=T.FK_resource_home and T.FK_bed_status = 2)) as OccupiedBeds

from dbo.resource_home H
)
Select * from MyTable
Where OpenBeds>=1;
0
 
LVL 1

Author Comment

by:HLRosenberger
ID: 40540443
got it! Thanks so much!
0
 
LVL 1

Author Closing Comment

by:HLRosenberger
ID: 40540444
Excellent!   Thanks so much!
0
 
LVL 48

Expert Comment

by:PortletPaul
ID: 40541441
>>" I'm unfamiliar with the WITH syntax."
WITH is used with "Common Table Expressions" (CTE)
These are extremely useful devices for "recursion" (e.g. in a hierarchy) or to avoid repeating a subquery over and over. In my view they should be used only for recursion or to avoid repetition.

It isn't required that you use WITH for your query. I wouldn't in this particular case as there is no benefit in doing so. All that is required is "nesting" the query (sometimes referred to as a "derived table") like this:
SELECT
      ID
    , number_of_beds
    , number_of_beds - OpenBeds AS OccupiedBeds
FROM (
            SELECT
                  H.ID
                , H.number_of_beds
                , (
                        SELECT
                              COUNT(*)
                        FROM dbo.resource_home_bed AS T
                        WHERE H.ID = T.FK_resource_home
                        AND T.FK_bed_status = 2
                  ) AS OpenBeds
            FROM dbo.resource_home H
      ) AS DERIVED
WHERE OpenBeds >= 1
;

Open in new window

In SQL Server there is also "cross apply" which is super handy for this:
SELECT
      H.ID
    , H.number_of_beds
    , CA.OpenBeds
    , H.number_of_beds - CA.OpenBeds AS OccupiedBeds
FROM dbo.resource_home H
      CROSS APPLY (
            SELECT
                  COUNT(*) AS OpenBeds
            FROM dbo.resource_home_bed AS T
            WHERE H.ID = T.FK_resource_home
            AND T.FK_bed_status = 2
      ) AS CA
;

Open in new window

0
 
LVL 48

Expert Comment

by:PortletPaul
ID: 40541559
@Phillip Burton

Congratulations on achieving Rookie of the Year for 2014.
0

Featured Post

Webinar: Aligning, Automating, Winning

Join Dan Russo, Senior Manager of Operations Intelligence, for an in-depth discussion on how Dealertrack, leading provider of integrated digital solutions for the automotive industry, transformed their DevOps processes to increase collaboration and move with greater velocity.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
Parsing a CSV file is a task that we are confronted with regularly, and although there are a vast number of means to do this, as a newbie, the field can be confusing and the tools can seem complex. A simple solution to parsing a customized CSV fi…
Two types of users will appreciate AOMEI Backupper Pro: 1 - Those with PCIe drives (and haven't found cloning software that works on them). 2 - Those who want a fast clone of their boot drive (no re-boots needed) and it can clone your drive wh…
This video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.

821 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question