T-sql select statement - multiple column with Case statement yes or no based on another table data










-4















I have a T-SQL select statement with multiple columns with Case statements yes or no based on another table data



I have these two tables:



table1



Id | Location
----+------------
101 | Warsaw
102 | Belfast
104 | Singapore
106 | Texas
108 | Mumbai
109 | Virgina


table2:



Id | AttrName | AttrId
----+------------+---------
101 | Datacenter | 99
101 | Cold | 88
102 | Datacenter | 99
102 | Cold | 88
106 | Datacenter | 99
108 | Cold | 88


The query output should be:



Id | Location | Datacenter | Cold 
----+-----------+------------+------
101 | Warsaw | YES | YES
102 | Belfast | YES | YES
104 | Singapore | NO | NO
106 | Texas | YES | NO
108 | Mumbai | NO | YES
109 | Virgina | NO | NO


Please let me know how we can achieve this.










share|improve this question
























  • Please read this for some tips on improving your question. And why the sp tag?

    – HABO
    Nov 14 '18 at 23:22







  • 3





    StackOverflow is not a code or SQL writing service. We expect you to make an effort to solve the problem yourself first. Once you've done so and run into difficulties, you can explain what you're trying to do and the problem you're having, include the relevant portions of your code, and ask a specific question related to that code, and we'll be glad to try to help. Your experiences here will be much better if you spend some time taking the tour and reading the help center pages, especially How to Ask, before you begin posting here.

    – Ken White
    Nov 14 '18 at 23:38











  • This is the query I have tried in isql and it worked. I'm working to accomplish in mssql. select a.id, a.Location,'Datacenter' =case when b1.AttrId=99 then 'yes' else 'No' end,'Cold'=case when b2.AttrId=88 then 'yes' else 'No' end from table1 a, (select Id,AttrId from table2 b where AttrId=99) b1, (select Id,AttrId from table2 b where AttrId=88) b2 where a.Id*=b1.Id and a.Id*=b2.Id

    – MTC Entertainment
    Nov 15 '18 at 12:27















-4















I have a T-SQL select statement with multiple columns with Case statements yes or no based on another table data



I have these two tables:



table1



Id | Location
----+------------
101 | Warsaw
102 | Belfast
104 | Singapore
106 | Texas
108 | Mumbai
109 | Virgina


table2:



Id | AttrName | AttrId
----+------------+---------
101 | Datacenter | 99
101 | Cold | 88
102 | Datacenter | 99
102 | Cold | 88
106 | Datacenter | 99
108 | Cold | 88


The query output should be:



Id | Location | Datacenter | Cold 
----+-----------+------------+------
101 | Warsaw | YES | YES
102 | Belfast | YES | YES
104 | Singapore | NO | NO
106 | Texas | YES | NO
108 | Mumbai | NO | YES
109 | Virgina | NO | NO


Please let me know how we can achieve this.










share|improve this question
























  • Please read this for some tips on improving your question. And why the sp tag?

    – HABO
    Nov 14 '18 at 23:22







  • 3





    StackOverflow is not a code or SQL writing service. We expect you to make an effort to solve the problem yourself first. Once you've done so and run into difficulties, you can explain what you're trying to do and the problem you're having, include the relevant portions of your code, and ask a specific question related to that code, and we'll be glad to try to help. Your experiences here will be much better if you spend some time taking the tour and reading the help center pages, especially How to Ask, before you begin posting here.

    – Ken White
    Nov 14 '18 at 23:38











  • This is the query I have tried in isql and it worked. I'm working to accomplish in mssql. select a.id, a.Location,'Datacenter' =case when b1.AttrId=99 then 'yes' else 'No' end,'Cold'=case when b2.AttrId=88 then 'yes' else 'No' end from table1 a, (select Id,AttrId from table2 b where AttrId=99) b1, (select Id,AttrId from table2 b where AttrId=88) b2 where a.Id*=b1.Id and a.Id*=b2.Id

    – MTC Entertainment
    Nov 15 '18 at 12:27













-4












-4








-4








I have a T-SQL select statement with multiple columns with Case statements yes or no based on another table data



I have these two tables:



table1



Id | Location
----+------------
101 | Warsaw
102 | Belfast
104 | Singapore
106 | Texas
108 | Mumbai
109 | Virgina


table2:



Id | AttrName | AttrId
----+------------+---------
101 | Datacenter | 99
101 | Cold | 88
102 | Datacenter | 99
102 | Cold | 88
106 | Datacenter | 99
108 | Cold | 88


The query output should be:



Id | Location | Datacenter | Cold 
----+-----------+------------+------
101 | Warsaw | YES | YES
102 | Belfast | YES | YES
104 | Singapore | NO | NO
106 | Texas | YES | NO
108 | Mumbai | NO | YES
109 | Virgina | NO | NO


Please let me know how we can achieve this.










share|improve this question
















I have a T-SQL select statement with multiple columns with Case statements yes or no based on another table data



I have these two tables:



table1



Id | Location
----+------------
101 | Warsaw
102 | Belfast
104 | Singapore
106 | Texas
108 | Mumbai
109 | Virgina


table2:



Id | AttrName | AttrId
----+------------+---------
101 | Datacenter | 99
101 | Cold | 88
102 | Datacenter | 99
102 | Cold | 88
106 | Datacenter | 99
108 | Cold | 88


The query output should be:



Id | Location | Datacenter | Cold 
----+-----------+------------+------
101 | Warsaw | YES | YES
102 | Belfast | YES | YES
104 | Singapore | NO | NO
106 | Texas | YES | NO
108 | Mumbai | NO | YES
109 | Virgina | NO | NO


Please let me know how we can achieve this.







sql-server tsql






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 15 '18 at 5:23









marc_s

579k12911181265




579k12911181265










asked Nov 14 '18 at 23:17









MTC EntertainmentMTC Entertainment

1




1












  • Please read this for some tips on improving your question. And why the sp tag?

    – HABO
    Nov 14 '18 at 23:22







  • 3





    StackOverflow is not a code or SQL writing service. We expect you to make an effort to solve the problem yourself first. Once you've done so and run into difficulties, you can explain what you're trying to do and the problem you're having, include the relevant portions of your code, and ask a specific question related to that code, and we'll be glad to try to help. Your experiences here will be much better if you spend some time taking the tour and reading the help center pages, especially How to Ask, before you begin posting here.

    – Ken White
    Nov 14 '18 at 23:38











  • This is the query I have tried in isql and it worked. I'm working to accomplish in mssql. select a.id, a.Location,'Datacenter' =case when b1.AttrId=99 then 'yes' else 'No' end,'Cold'=case when b2.AttrId=88 then 'yes' else 'No' end from table1 a, (select Id,AttrId from table2 b where AttrId=99) b1, (select Id,AttrId from table2 b where AttrId=88) b2 where a.Id*=b1.Id and a.Id*=b2.Id

    – MTC Entertainment
    Nov 15 '18 at 12:27

















  • Please read this for some tips on improving your question. And why the sp tag?

    – HABO
    Nov 14 '18 at 23:22







  • 3





    StackOverflow is not a code or SQL writing service. We expect you to make an effort to solve the problem yourself first. Once you've done so and run into difficulties, you can explain what you're trying to do and the problem you're having, include the relevant portions of your code, and ask a specific question related to that code, and we'll be glad to try to help. Your experiences here will be much better if you spend some time taking the tour and reading the help center pages, especially How to Ask, before you begin posting here.

    – Ken White
    Nov 14 '18 at 23:38











  • This is the query I have tried in isql and it worked. I'm working to accomplish in mssql. select a.id, a.Location,'Datacenter' =case when b1.AttrId=99 then 'yes' else 'No' end,'Cold'=case when b2.AttrId=88 then 'yes' else 'No' end from table1 a, (select Id,AttrId from table2 b where AttrId=99) b1, (select Id,AttrId from table2 b where AttrId=88) b2 where a.Id*=b1.Id and a.Id*=b2.Id

    – MTC Entertainment
    Nov 15 '18 at 12:27
















Please read this for some tips on improving your question. And why the sp tag?

– HABO
Nov 14 '18 at 23:22






Please read this for some tips on improving your question. And why the sp tag?

– HABO
Nov 14 '18 at 23:22





3




3





StackOverflow is not a code or SQL writing service. We expect you to make an effort to solve the problem yourself first. Once you've done so and run into difficulties, you can explain what you're trying to do and the problem you're having, include the relevant portions of your code, and ask a specific question related to that code, and we'll be glad to try to help. Your experiences here will be much better if you spend some time taking the tour and reading the help center pages, especially How to Ask, before you begin posting here.

– Ken White
Nov 14 '18 at 23:38





StackOverflow is not a code or SQL writing service. We expect you to make an effort to solve the problem yourself first. Once you've done so and run into difficulties, you can explain what you're trying to do and the problem you're having, include the relevant portions of your code, and ask a specific question related to that code, and we'll be glad to try to help. Your experiences here will be much better if you spend some time taking the tour and reading the help center pages, especially How to Ask, before you begin posting here.

– Ken White
Nov 14 '18 at 23:38













This is the query I have tried in isql and it worked. I'm working to accomplish in mssql. select a.id, a.Location,'Datacenter' =case when b1.AttrId=99 then 'yes' else 'No' end,'Cold'=case when b2.AttrId=88 then 'yes' else 'No' end from table1 a, (select Id,AttrId from table2 b where AttrId=99) b1, (select Id,AttrId from table2 b where AttrId=88) b2 where a.Id*=b1.Id and a.Id*=b2.Id

– MTC Entertainment
Nov 15 '18 at 12:27





This is the query I have tried in isql and it worked. I'm working to accomplish in mssql. select a.id, a.Location,'Datacenter' =case when b1.AttrId=99 then 'yes' else 'No' end,'Cold'=case when b2.AttrId=88 then 'yes' else 'No' end from table1 a, (select Id,AttrId from table2 b where AttrId=99) b1, (select Id,AttrId from table2 b where AttrId=88) b2 where a.Id*=b1.Id and a.Id*=b2.Id

– MTC Entertainment
Nov 15 '18 at 12:27












3 Answers
3






active

oldest

votes


















0














I'd use PIVOT instead. It can perform better, but I'd check the execution plans on each to be sure. Just be sure to redirect my query to the real tables (instead of these table variables for testing) before you compare plans. Good luck! :)



DECLARE @Table1 TABLE (
Id BIGINT NOT NULL PRIMARY KEY,
Location VARCHAR(100) NOT NULL,
UNIQUE CLUSTERED (Id)
);

INSERT INTO @Table1
(Id, Location)
VALUES
(101,'Warsaw'),
(102,'Belfast'),
(104,'Singapore'),
(106,'Texas'),
(108,'Mumbai'),
(109,'Virgina');

DECLARE @Table2 TABLE (
Id BIGINT NOT NULL,
AttrName VARCHAR(100) NOT NULL,
AttrId BIGINT NOT NULL,
UNIQUE CLUSTERED (Id,AttrId)
);

INSERT INTO @Table2
(Id, AttrName, AttrId)
VALUES
(101,'Datacenter',99),
(101,'Cold',88),
(102,'Datacenter',99),
(102,'Cold',88),
(106,'Datacenter',99),
(108,'Cold',88);

WITH CTE_Table2 AS (
SELECT
Id,
Datacenter,
Cold
FROM (
SELECT
t.Id,
t.AttrName,
'YES' AS Bool
FROM @Table2 AS t
) AS b
PIVOT (
MAX(Bool)
FOR AttrName IN ([Datacenter],[Cold])
) AS p
)

SELECT
t1.Id,
t1.Location,
ISNULL(t2.Datacenter,'NO') AS Datacenter,
ISNULL(t2.Cold,'NO') AS Cold
FROM @Table1 AS t1
LEFT JOIN CTE_Table2 AS t2
ON t1.Id = t2.Id;





share|improve this answer

























  • As an extra note here... the comments on your main post about putting in real effort is important. The only reason I'm helping in this case is because you're new to SO. It takes some getting used to. I hope my SQL can actually help your situation.

    – Utrolig
    Nov 15 '18 at 8:33











  • Thank you. I have tried to update my comments with the query I have used before in isql ( it works) but in mssql it's not working. Also I want to update the query in my question, it's not allowing to update it( Format issue).

    – MTC Entertainment
    Nov 15 '18 at 12:25











  • Sorry @MTCEntertainment, does that mean this worked for you? Do you still need assistance?

    – Utrolig
    Nov 15 '18 at 17:19


















0














Below is other option to resolve, it uses EXISTS,



-- delcare table variables
declare @t1 table (Id int, Location nvarchar(20))
declare @t2 table (Id int, AttrName nvarchar(20), AttrId int)

-- insert test data
insert into @t1
values (101, 'Warsaw'),
(102, 'Beflast'),
(104, 'Singapore'),
(106, 'Texas'),
(108, 'Mumbai'),
(109, 'Virginia')

insert into @t2
values (101, 'Datacentre', 99),
(101, 'Cold', 88),
(102, 'Datacentre', 99),
(102, 'Cold', 88),
(106, 'Datacentre', 99),
(108, 'Cold', 88)

-- query
select
t1.Id,
Location,
case when exists (select 1 from @t2 t2 where t2.AttrId = 99 and t1.id = t2.id) then 'yes' else 'no' end as Datacentre,
case when exists (select 1 from @t2 t2 where t2.AttrId = 88 and t1.id = t2.id) then 'yes' else 'no' end as Cold
from @t1 t1


Result



Id Location Datacentre Cold
101 Warsaw yes yes
102 Beflast yes yes
104 Singapore no no
106 Texas yes no
108 Mumbai no yes
109 Virginia no no





share|improve this answer

























  • Thank you. let me try this.

    – MTC Entertainment
    Nov 15 '18 at 12:25











  • @MTCEntertainment, add comment if something is unclear.

    – Pawel Czapski
    Nov 15 '18 at 13:16


















0














  1. Simple but not optimized approach: You need to LEFT OUTER JOIN table2 to table1 as many times as many AttrName's you would like to put in different columns in the final result. Each join should use a different alias name for table2 and filter on a specific AttrName:

FROM table1 as base
LEFT OUTER JOIN table2 as Datacenter on base.Id = Datacenter.Id and Datacenter.AttrName = 'Datacenter'
LEFT OUTER JOIN table2 as Cold on base.Id = Cold.Id and Cold.AttrName = 'Cold'


In the SELECT you need to check for the existence of matching lookup to the specific alias of table2 to define a column deriving from AttrName:



CASE WHEN Datacenter.Id IS NOT NULL THEN 'YES' ELSE 'NO' END as Datacenter


  1. Advanced and likely more optimized approach:

    Use Utrolig's answer: PIVOT should outperform due to less lookups (but always look at query plans when you optimize code!)





share|improve this answer
























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53310200%2ft-sql-select-statement-multiple-column-with-case-statement-yes-or-no-based-on%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    3 Answers
    3






    active

    oldest

    votes








    3 Answers
    3






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    I'd use PIVOT instead. It can perform better, but I'd check the execution plans on each to be sure. Just be sure to redirect my query to the real tables (instead of these table variables for testing) before you compare plans. Good luck! :)



    DECLARE @Table1 TABLE (
    Id BIGINT NOT NULL PRIMARY KEY,
    Location VARCHAR(100) NOT NULL,
    UNIQUE CLUSTERED (Id)
    );

    INSERT INTO @Table1
    (Id, Location)
    VALUES
    (101,'Warsaw'),
    (102,'Belfast'),
    (104,'Singapore'),
    (106,'Texas'),
    (108,'Mumbai'),
    (109,'Virgina');

    DECLARE @Table2 TABLE (
    Id BIGINT NOT NULL,
    AttrName VARCHAR(100) NOT NULL,
    AttrId BIGINT NOT NULL,
    UNIQUE CLUSTERED (Id,AttrId)
    );

    INSERT INTO @Table2
    (Id, AttrName, AttrId)
    VALUES
    (101,'Datacenter',99),
    (101,'Cold',88),
    (102,'Datacenter',99),
    (102,'Cold',88),
    (106,'Datacenter',99),
    (108,'Cold',88);

    WITH CTE_Table2 AS (
    SELECT
    Id,
    Datacenter,
    Cold
    FROM (
    SELECT
    t.Id,
    t.AttrName,
    'YES' AS Bool
    FROM @Table2 AS t
    ) AS b
    PIVOT (
    MAX(Bool)
    FOR AttrName IN ([Datacenter],[Cold])
    ) AS p
    )

    SELECT
    t1.Id,
    t1.Location,
    ISNULL(t2.Datacenter,'NO') AS Datacenter,
    ISNULL(t2.Cold,'NO') AS Cold
    FROM @Table1 AS t1
    LEFT JOIN CTE_Table2 AS t2
    ON t1.Id = t2.Id;





    share|improve this answer

























    • As an extra note here... the comments on your main post about putting in real effort is important. The only reason I'm helping in this case is because you're new to SO. It takes some getting used to. I hope my SQL can actually help your situation.

      – Utrolig
      Nov 15 '18 at 8:33











    • Thank you. I have tried to update my comments with the query I have used before in isql ( it works) but in mssql it's not working. Also I want to update the query in my question, it's not allowing to update it( Format issue).

      – MTC Entertainment
      Nov 15 '18 at 12:25











    • Sorry @MTCEntertainment, does that mean this worked for you? Do you still need assistance?

      – Utrolig
      Nov 15 '18 at 17:19















    0














    I'd use PIVOT instead. It can perform better, but I'd check the execution plans on each to be sure. Just be sure to redirect my query to the real tables (instead of these table variables for testing) before you compare plans. Good luck! :)



    DECLARE @Table1 TABLE (
    Id BIGINT NOT NULL PRIMARY KEY,
    Location VARCHAR(100) NOT NULL,
    UNIQUE CLUSTERED (Id)
    );

    INSERT INTO @Table1
    (Id, Location)
    VALUES
    (101,'Warsaw'),
    (102,'Belfast'),
    (104,'Singapore'),
    (106,'Texas'),
    (108,'Mumbai'),
    (109,'Virgina');

    DECLARE @Table2 TABLE (
    Id BIGINT NOT NULL,
    AttrName VARCHAR(100) NOT NULL,
    AttrId BIGINT NOT NULL,
    UNIQUE CLUSTERED (Id,AttrId)
    );

    INSERT INTO @Table2
    (Id, AttrName, AttrId)
    VALUES
    (101,'Datacenter',99),
    (101,'Cold',88),
    (102,'Datacenter',99),
    (102,'Cold',88),
    (106,'Datacenter',99),
    (108,'Cold',88);

    WITH CTE_Table2 AS (
    SELECT
    Id,
    Datacenter,
    Cold
    FROM (
    SELECT
    t.Id,
    t.AttrName,
    'YES' AS Bool
    FROM @Table2 AS t
    ) AS b
    PIVOT (
    MAX(Bool)
    FOR AttrName IN ([Datacenter],[Cold])
    ) AS p
    )

    SELECT
    t1.Id,
    t1.Location,
    ISNULL(t2.Datacenter,'NO') AS Datacenter,
    ISNULL(t2.Cold,'NO') AS Cold
    FROM @Table1 AS t1
    LEFT JOIN CTE_Table2 AS t2
    ON t1.Id = t2.Id;





    share|improve this answer

























    • As an extra note here... the comments on your main post about putting in real effort is important. The only reason I'm helping in this case is because you're new to SO. It takes some getting used to. I hope my SQL can actually help your situation.

      – Utrolig
      Nov 15 '18 at 8:33











    • Thank you. I have tried to update my comments with the query I have used before in isql ( it works) but in mssql it's not working. Also I want to update the query in my question, it's not allowing to update it( Format issue).

      – MTC Entertainment
      Nov 15 '18 at 12:25











    • Sorry @MTCEntertainment, does that mean this worked for you? Do you still need assistance?

      – Utrolig
      Nov 15 '18 at 17:19













    0












    0








    0







    I'd use PIVOT instead. It can perform better, but I'd check the execution plans on each to be sure. Just be sure to redirect my query to the real tables (instead of these table variables for testing) before you compare plans. Good luck! :)



    DECLARE @Table1 TABLE (
    Id BIGINT NOT NULL PRIMARY KEY,
    Location VARCHAR(100) NOT NULL,
    UNIQUE CLUSTERED (Id)
    );

    INSERT INTO @Table1
    (Id, Location)
    VALUES
    (101,'Warsaw'),
    (102,'Belfast'),
    (104,'Singapore'),
    (106,'Texas'),
    (108,'Mumbai'),
    (109,'Virgina');

    DECLARE @Table2 TABLE (
    Id BIGINT NOT NULL,
    AttrName VARCHAR(100) NOT NULL,
    AttrId BIGINT NOT NULL,
    UNIQUE CLUSTERED (Id,AttrId)
    );

    INSERT INTO @Table2
    (Id, AttrName, AttrId)
    VALUES
    (101,'Datacenter',99),
    (101,'Cold',88),
    (102,'Datacenter',99),
    (102,'Cold',88),
    (106,'Datacenter',99),
    (108,'Cold',88);

    WITH CTE_Table2 AS (
    SELECT
    Id,
    Datacenter,
    Cold
    FROM (
    SELECT
    t.Id,
    t.AttrName,
    'YES' AS Bool
    FROM @Table2 AS t
    ) AS b
    PIVOT (
    MAX(Bool)
    FOR AttrName IN ([Datacenter],[Cold])
    ) AS p
    )

    SELECT
    t1.Id,
    t1.Location,
    ISNULL(t2.Datacenter,'NO') AS Datacenter,
    ISNULL(t2.Cold,'NO') AS Cold
    FROM @Table1 AS t1
    LEFT JOIN CTE_Table2 AS t2
    ON t1.Id = t2.Id;





    share|improve this answer















    I'd use PIVOT instead. It can perform better, but I'd check the execution plans on each to be sure. Just be sure to redirect my query to the real tables (instead of these table variables for testing) before you compare plans. Good luck! :)



    DECLARE @Table1 TABLE (
    Id BIGINT NOT NULL PRIMARY KEY,
    Location VARCHAR(100) NOT NULL,
    UNIQUE CLUSTERED (Id)
    );

    INSERT INTO @Table1
    (Id, Location)
    VALUES
    (101,'Warsaw'),
    (102,'Belfast'),
    (104,'Singapore'),
    (106,'Texas'),
    (108,'Mumbai'),
    (109,'Virgina');

    DECLARE @Table2 TABLE (
    Id BIGINT NOT NULL,
    AttrName VARCHAR(100) NOT NULL,
    AttrId BIGINT NOT NULL,
    UNIQUE CLUSTERED (Id,AttrId)
    );

    INSERT INTO @Table2
    (Id, AttrName, AttrId)
    VALUES
    (101,'Datacenter',99),
    (101,'Cold',88),
    (102,'Datacenter',99),
    (102,'Cold',88),
    (106,'Datacenter',99),
    (108,'Cold',88);

    WITH CTE_Table2 AS (
    SELECT
    Id,
    Datacenter,
    Cold
    FROM (
    SELECT
    t.Id,
    t.AttrName,
    'YES' AS Bool
    FROM @Table2 AS t
    ) AS b
    PIVOT (
    MAX(Bool)
    FOR AttrName IN ([Datacenter],[Cold])
    ) AS p
    )

    SELECT
    t1.Id,
    t1.Location,
    ISNULL(t2.Datacenter,'NO') AS Datacenter,
    ISNULL(t2.Cold,'NO') AS Cold
    FROM @Table1 AS t1
    LEFT JOIN CTE_Table2 AS t2
    ON t1.Id = t2.Id;






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 15 '18 at 8:51

























    answered Nov 15 '18 at 8:08









    UtroligUtrolig

    241211




    241211












    • As an extra note here... the comments on your main post about putting in real effort is important. The only reason I'm helping in this case is because you're new to SO. It takes some getting used to. I hope my SQL can actually help your situation.

      – Utrolig
      Nov 15 '18 at 8:33











    • Thank you. I have tried to update my comments with the query I have used before in isql ( it works) but in mssql it's not working. Also I want to update the query in my question, it's not allowing to update it( Format issue).

      – MTC Entertainment
      Nov 15 '18 at 12:25











    • Sorry @MTCEntertainment, does that mean this worked for you? Do you still need assistance?

      – Utrolig
      Nov 15 '18 at 17:19

















    • As an extra note here... the comments on your main post about putting in real effort is important. The only reason I'm helping in this case is because you're new to SO. It takes some getting used to. I hope my SQL can actually help your situation.

      – Utrolig
      Nov 15 '18 at 8:33











    • Thank you. I have tried to update my comments with the query I have used before in isql ( it works) but in mssql it's not working. Also I want to update the query in my question, it's not allowing to update it( Format issue).

      – MTC Entertainment
      Nov 15 '18 at 12:25











    • Sorry @MTCEntertainment, does that mean this worked for you? Do you still need assistance?

      – Utrolig
      Nov 15 '18 at 17:19
















    As an extra note here... the comments on your main post about putting in real effort is important. The only reason I'm helping in this case is because you're new to SO. It takes some getting used to. I hope my SQL can actually help your situation.

    – Utrolig
    Nov 15 '18 at 8:33





    As an extra note here... the comments on your main post about putting in real effort is important. The only reason I'm helping in this case is because you're new to SO. It takes some getting used to. I hope my SQL can actually help your situation.

    – Utrolig
    Nov 15 '18 at 8:33













    Thank you. I have tried to update my comments with the query I have used before in isql ( it works) but in mssql it's not working. Also I want to update the query in my question, it's not allowing to update it( Format issue).

    – MTC Entertainment
    Nov 15 '18 at 12:25





    Thank you. I have tried to update my comments with the query I have used before in isql ( it works) but in mssql it's not working. Also I want to update the query in my question, it's not allowing to update it( Format issue).

    – MTC Entertainment
    Nov 15 '18 at 12:25













    Sorry @MTCEntertainment, does that mean this worked for you? Do you still need assistance?

    – Utrolig
    Nov 15 '18 at 17:19





    Sorry @MTCEntertainment, does that mean this worked for you? Do you still need assistance?

    – Utrolig
    Nov 15 '18 at 17:19













    0














    Below is other option to resolve, it uses EXISTS,



    -- delcare table variables
    declare @t1 table (Id int, Location nvarchar(20))
    declare @t2 table (Id int, AttrName nvarchar(20), AttrId int)

    -- insert test data
    insert into @t1
    values (101, 'Warsaw'),
    (102, 'Beflast'),
    (104, 'Singapore'),
    (106, 'Texas'),
    (108, 'Mumbai'),
    (109, 'Virginia')

    insert into @t2
    values (101, 'Datacentre', 99),
    (101, 'Cold', 88),
    (102, 'Datacentre', 99),
    (102, 'Cold', 88),
    (106, 'Datacentre', 99),
    (108, 'Cold', 88)

    -- query
    select
    t1.Id,
    Location,
    case when exists (select 1 from @t2 t2 where t2.AttrId = 99 and t1.id = t2.id) then 'yes' else 'no' end as Datacentre,
    case when exists (select 1 from @t2 t2 where t2.AttrId = 88 and t1.id = t2.id) then 'yes' else 'no' end as Cold
    from @t1 t1


    Result



    Id Location Datacentre Cold
    101 Warsaw yes yes
    102 Beflast yes yes
    104 Singapore no no
    106 Texas yes no
    108 Mumbai no yes
    109 Virginia no no





    share|improve this answer

























    • Thank you. let me try this.

      – MTC Entertainment
      Nov 15 '18 at 12:25











    • @MTCEntertainment, add comment if something is unclear.

      – Pawel Czapski
      Nov 15 '18 at 13:16















    0














    Below is other option to resolve, it uses EXISTS,



    -- delcare table variables
    declare @t1 table (Id int, Location nvarchar(20))
    declare @t2 table (Id int, AttrName nvarchar(20), AttrId int)

    -- insert test data
    insert into @t1
    values (101, 'Warsaw'),
    (102, 'Beflast'),
    (104, 'Singapore'),
    (106, 'Texas'),
    (108, 'Mumbai'),
    (109, 'Virginia')

    insert into @t2
    values (101, 'Datacentre', 99),
    (101, 'Cold', 88),
    (102, 'Datacentre', 99),
    (102, 'Cold', 88),
    (106, 'Datacentre', 99),
    (108, 'Cold', 88)

    -- query
    select
    t1.Id,
    Location,
    case when exists (select 1 from @t2 t2 where t2.AttrId = 99 and t1.id = t2.id) then 'yes' else 'no' end as Datacentre,
    case when exists (select 1 from @t2 t2 where t2.AttrId = 88 and t1.id = t2.id) then 'yes' else 'no' end as Cold
    from @t1 t1


    Result



    Id Location Datacentre Cold
    101 Warsaw yes yes
    102 Beflast yes yes
    104 Singapore no no
    106 Texas yes no
    108 Mumbai no yes
    109 Virginia no no





    share|improve this answer

























    • Thank you. let me try this.

      – MTC Entertainment
      Nov 15 '18 at 12:25











    • @MTCEntertainment, add comment if something is unclear.

      – Pawel Czapski
      Nov 15 '18 at 13:16













    0












    0








    0







    Below is other option to resolve, it uses EXISTS,



    -- delcare table variables
    declare @t1 table (Id int, Location nvarchar(20))
    declare @t2 table (Id int, AttrName nvarchar(20), AttrId int)

    -- insert test data
    insert into @t1
    values (101, 'Warsaw'),
    (102, 'Beflast'),
    (104, 'Singapore'),
    (106, 'Texas'),
    (108, 'Mumbai'),
    (109, 'Virginia')

    insert into @t2
    values (101, 'Datacentre', 99),
    (101, 'Cold', 88),
    (102, 'Datacentre', 99),
    (102, 'Cold', 88),
    (106, 'Datacentre', 99),
    (108, 'Cold', 88)

    -- query
    select
    t1.Id,
    Location,
    case when exists (select 1 from @t2 t2 where t2.AttrId = 99 and t1.id = t2.id) then 'yes' else 'no' end as Datacentre,
    case when exists (select 1 from @t2 t2 where t2.AttrId = 88 and t1.id = t2.id) then 'yes' else 'no' end as Cold
    from @t1 t1


    Result



    Id Location Datacentre Cold
    101 Warsaw yes yes
    102 Beflast yes yes
    104 Singapore no no
    106 Texas yes no
    108 Mumbai no yes
    109 Virginia no no





    share|improve this answer















    Below is other option to resolve, it uses EXISTS,



    -- delcare table variables
    declare @t1 table (Id int, Location nvarchar(20))
    declare @t2 table (Id int, AttrName nvarchar(20), AttrId int)

    -- insert test data
    insert into @t1
    values (101, 'Warsaw'),
    (102, 'Beflast'),
    (104, 'Singapore'),
    (106, 'Texas'),
    (108, 'Mumbai'),
    (109, 'Virginia')

    insert into @t2
    values (101, 'Datacentre', 99),
    (101, 'Cold', 88),
    (102, 'Datacentre', 99),
    (102, 'Cold', 88),
    (106, 'Datacentre', 99),
    (108, 'Cold', 88)

    -- query
    select
    t1.Id,
    Location,
    case when exists (select 1 from @t2 t2 where t2.AttrId = 99 and t1.id = t2.id) then 'yes' else 'no' end as Datacentre,
    case when exists (select 1 from @t2 t2 where t2.AttrId = 88 and t1.id = t2.id) then 'yes' else 'no' end as Cold
    from @t1 t1


    Result



    Id Location Datacentre Cold
    101 Warsaw yes yes
    102 Beflast yes yes
    104 Singapore no no
    106 Texas yes no
    108 Mumbai no yes
    109 Virginia no no






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 15 '18 at 8:58









    Dávid Laczkó

    429128




    429128










    answered Nov 15 '18 at 8:33









    Pawel CzapskiPawel Czapski

    1,3371917




    1,3371917












    • Thank you. let me try this.

      – MTC Entertainment
      Nov 15 '18 at 12:25











    • @MTCEntertainment, add comment if something is unclear.

      – Pawel Czapski
      Nov 15 '18 at 13:16

















    • Thank you. let me try this.

      – MTC Entertainment
      Nov 15 '18 at 12:25











    • @MTCEntertainment, add comment if something is unclear.

      – Pawel Czapski
      Nov 15 '18 at 13:16
















    Thank you. let me try this.

    – MTC Entertainment
    Nov 15 '18 at 12:25





    Thank you. let me try this.

    – MTC Entertainment
    Nov 15 '18 at 12:25













    @MTCEntertainment, add comment if something is unclear.

    – Pawel Czapski
    Nov 15 '18 at 13:16





    @MTCEntertainment, add comment if something is unclear.

    – Pawel Czapski
    Nov 15 '18 at 13:16











    0














    1. Simple but not optimized approach: You need to LEFT OUTER JOIN table2 to table1 as many times as many AttrName's you would like to put in different columns in the final result. Each join should use a different alias name for table2 and filter on a specific AttrName:

    FROM table1 as base
    LEFT OUTER JOIN table2 as Datacenter on base.Id = Datacenter.Id and Datacenter.AttrName = 'Datacenter'
    LEFT OUTER JOIN table2 as Cold on base.Id = Cold.Id and Cold.AttrName = 'Cold'


    In the SELECT you need to check for the existence of matching lookup to the specific alias of table2 to define a column deriving from AttrName:



    CASE WHEN Datacenter.Id IS NOT NULL THEN 'YES' ELSE 'NO' END as Datacenter


    1. Advanced and likely more optimized approach:

      Use Utrolig's answer: PIVOT should outperform due to less lookups (but always look at query plans when you optimize code!)





    share|improve this answer





























      0














      1. Simple but not optimized approach: You need to LEFT OUTER JOIN table2 to table1 as many times as many AttrName's you would like to put in different columns in the final result. Each join should use a different alias name for table2 and filter on a specific AttrName:

      FROM table1 as base
      LEFT OUTER JOIN table2 as Datacenter on base.Id = Datacenter.Id and Datacenter.AttrName = 'Datacenter'
      LEFT OUTER JOIN table2 as Cold on base.Id = Cold.Id and Cold.AttrName = 'Cold'


      In the SELECT you need to check for the existence of matching lookup to the specific alias of table2 to define a column deriving from AttrName:



      CASE WHEN Datacenter.Id IS NOT NULL THEN 'YES' ELSE 'NO' END as Datacenter


      1. Advanced and likely more optimized approach:

        Use Utrolig's answer: PIVOT should outperform due to less lookups (but always look at query plans when you optimize code!)





      share|improve this answer



























        0












        0








        0







        1. Simple but not optimized approach: You need to LEFT OUTER JOIN table2 to table1 as many times as many AttrName's you would like to put in different columns in the final result. Each join should use a different alias name for table2 and filter on a specific AttrName:

        FROM table1 as base
        LEFT OUTER JOIN table2 as Datacenter on base.Id = Datacenter.Id and Datacenter.AttrName = 'Datacenter'
        LEFT OUTER JOIN table2 as Cold on base.Id = Cold.Id and Cold.AttrName = 'Cold'


        In the SELECT you need to check for the existence of matching lookup to the specific alias of table2 to define a column deriving from AttrName:



        CASE WHEN Datacenter.Id IS NOT NULL THEN 'YES' ELSE 'NO' END as Datacenter


        1. Advanced and likely more optimized approach:

          Use Utrolig's answer: PIVOT should outperform due to less lookups (but always look at query plans when you optimize code!)





        share|improve this answer















        1. Simple but not optimized approach: You need to LEFT OUTER JOIN table2 to table1 as many times as many AttrName's you would like to put in different columns in the final result. Each join should use a different alias name for table2 and filter on a specific AttrName:

        FROM table1 as base
        LEFT OUTER JOIN table2 as Datacenter on base.Id = Datacenter.Id and Datacenter.AttrName = 'Datacenter'
        LEFT OUTER JOIN table2 as Cold on base.Id = Cold.Id and Cold.AttrName = 'Cold'


        In the SELECT you need to check for the existence of matching lookup to the specific alias of table2 to define a column deriving from AttrName:



        CASE WHEN Datacenter.Id IS NOT NULL THEN 'YES' ELSE 'NO' END as Datacenter


        1. Advanced and likely more optimized approach:

          Use Utrolig's answer: PIVOT should outperform due to less lookups (but always look at query plans when you optimize code!)






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 15 '18 at 9:25

























        answered Nov 15 '18 at 8:02









        Dávid LaczkóDávid Laczkó

        429128




        429128



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53310200%2ft-sql-select-statement-multiple-column-with-case-statement-yes-or-no-based-on%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            這個網誌中的熱門文章

            How to read a connectionString WITH PROVIDER in .NET Core?

            In R, how to develop a multiplot heatmap.2 figure showing key labels successfully

            Museum of Modern and Contemporary Art of Trento and Rovereto