Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

Problem with a Sub-SELECT statement. Need Help...

$
0
0

Hi there everybody.

First of all, the following DB schema is not mine and I have to work with it, and I'm not allowed to modify it.

Let's say I've got 3 tables :

- A list of Persons.
- A list of Services.
- A list of "Services Assignments" : <who> does <what> with a start datetime and an end datetime.

In real case I've got many more columns, but this example is just to keep things as simple as I can.

--> Table Persons :
[ID] [int] NOT NULL PRIMARY KEY
[Name] [nvarchar] (50) NOT NULL
[Code] [nvarchar] (50) NOT NULL

--> Table Services :
[ID] [int] NOT NULL PRIMARY KEY
[Name] [nvarchar] (50) NOT NULL
[Code] [nvarchar] (50) NOT NULL

--> Table ServicesAssignment :
[ServiceCode] [nvarchar] (50) NOT NULL PRIMARY KEY
[PersonCode] [nvarchar] (50) NOT NULL PRIMARY KEY
[DateServiceStart] [nvarchar] (14) NOT NULL
[DateServiceEnd] [nvarchar] (14) NULL

This table has a Two-Column Primary Key.
DateTime Fields are actually strings. Each Datetime string is made of 14 chars : yyyyMMddHHmmss.

I need queries that tell me the number of assignments which are "Active" ( DateServiceEnd IS NULL )
and number of assignments "Not-Active" ( DateServiceEnd IS NOT NULL ).

From the point of view of the Service the query should return all fields from the Services table :
SELECT * FROM Services
adding two columns for each Service returned,
the first as a count of "Active assignments" :

SELECT COUNT (ServiceCode)
FROM ServicesAssignment
WHERE ServiceCode = <Main Query Service Code>
AND DateServiceEnd IS NULL

and the second as a count of "Non-Active Assignments" :

SELECT COUNT (ServiceCode)
FROM ServicesAssignment
WHERE ServiceCode = <Main Query Service Code>
AND DateServiceEnd IS NOT NULL

I think I shold have one main query that shows all Services and two sub-queries, one for each column added.
Is this possible ? And how ?

Thanks to anyone able to help.




Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>