Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL - calculate a boolean field on the fly

I'm using SQL Server 2008.

Let's say I have two hypothetical tables like below:

CREATE TABLE [Department](
    [Id]            int    IDENTITY(1,1),
    [ManagerId]     int    NULL, -- << Foreign key to the Person table
    -- other fields
)

CREATE TABLE [Person](
    [Id]            int    IDENTITY(1,1),
    [DepartmentId]  int    NOT NULL, -- << Foreign key to the Department table
    -- other fields
)

Now, I want to return a list of rows from the [Person] table (i.e. list of staff for a given department). Only one (or zero) of these rows will match the [ManagerId] field in the [Department] table. And I want to flag the matched row with a boolean field on the fly... the resultant rowset will resemble the following schema:

[Id]        INT,
[IsManager] BIT NOT NULL DEFAULT 0,
-- other fields

The [IsManager] field will be TRUE when [Department].[ManagerId] matches [Person].[Id].

This is fairly trivial to do with two (or more) queries. But how can I achieve this using a single SQL statement?

like image 475
invarbrass Avatar asked Dec 05 '25 20:12

invarbrass


1 Answers

Add an expression to your SELECT clause where you compare actual persons Id with ManagerId from persons department

SELECT
    Person.Id,
    Department.Id,
    CAST(CASE WHEN Person.Id=Department.ManagerId THEN 1 ELSE 0 END AS BIT) AS IsManager
FROM Person
INNER JOIN Department ON Person.DepartmentId=Department.Id
WHERE Person.DepartmentId=<CONDITION>
like image 63
rabudde Avatar answered Dec 08 '25 10:12

rabudde



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!