/// Frank Hagen: Professional Web Developer, C# User, Reformed Über-geek RSS 2.0
# Tuesday, July 03, 2007

I am not a great T-SQL developer, so I frequently struggle with some of the more advanced queries.  I spent some time building the query below, so I want to post it for future reference and the hope it may help someone else.

Say you have a dependant table for lookup values of status.  The status code in the primary table may be 1, 2, 3, etc., so the lookup table will define them as Open, Closed, Pending, whatever.  Now say for reporting you want to know how many Open or Closed items you have in the table.  The SQL query below will return each Status name with a count of items using the codes in the primary table:

SELECT OS.ObjectStateID, OS.Code, OS.Name,
    (SELECT COUNT(RS.ProductRequestID)
       FROM ProductRequestState RS
      WHERE RS.IsCurrent = 1 AND RS.ObjectStateID = OS.ObjectStateID
    )
FROM ObjectState OS
Where OS.IsActive = 1

The output will look something like this:

  OID Code              Name                              Count  
----- ----------------- --------------------------------- -----   
    1 WaitSubmit        Created                             154 
    3 Rejected          Rejected                           4785 
    4 WaitTSTechRvw     Waiting TS Tech Review               68 
    6 WaitGroupApprv    Waiting Cost/Labor/TS Tech Apprv    228 
    8 WaitExecApprv     Waiting Manager/Executive Apprv       0 
   13 Complete          Complete                          14433 
   14 WaitCostApprv     Waiting Cost Accounting Apprv         0 
   15 WaitLaborApprv    Waiting Labor and Supply Apprv        0 
   16 WaitTSTechApprv   Waiting TS Technologist Apprv         0
Sorry for the ugly formatting, WordPress is a bit limiting.
Tuesday, July 03, 2007 2:47:47 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [0] -
SQL
All comments require the approval of the site owner before being displayed.
OpenID
Please login with either your OpenID above, or your details below.
Name
E-mail
(will show your gravatar icon)
Home page

Comment (Some html is allowed: b, blockquote@cite, i, strike, strong, u) where the @ means "attribute." For example, you can use <a href="" title=""> or <blockquote cite="Scott">.  

Enter the code shown (prevents robots):

Live Comment Preview
<%--
--%>
Statistics
Total Posts: 186
This Year: 0
This Month: 0
This Week: 0
Comments: 72
Locations of visitors to this page
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2010
Frank W Hagen
Sign In
All Content © 2010, Frank W Hagen
Custom DasBlog theme based on 'Business' by Christoph De Baene