SQL Server : except with results from both datasets












0















I have the following tables:



Stores:



StoreID | Name
1 | Store1
2 | Store2
3 | Store3

EmID | StoreID
1 | 1
2 | 1
3 | 1
1 | 2
3 | 2


Employee:



EmID | Employee | Important
1 | Cashier | 1
2 | Manager | 1
3 | Guard | 0


I need a query to return StoreID and EmID where Employee is important (Important = 1) and the store and employee are not connected. Basically, the result should be:



StoreID | EmId
--------+-------
2 | 2
3 | 1
3 | 2


I have tried joins, outer joins / apply-es, except, cte, temporary tables, but still haven't found the answer.



Can someone help me with the code, or at least point me in the right direction?
Any idea will be very much appreciated.



Thanks.










share|improve this question

























  • You can do this by using CROSS JOIN and LEFT JOIN. Check my answer below

    – Thilina Nakkawita
    Nov 14 '18 at 8:57
















0















I have the following tables:



Stores:



StoreID | Name
1 | Store1
2 | Store2
3 | Store3

EmID | StoreID
1 | 1
2 | 1
3 | 1
1 | 2
3 | 2


Employee:



EmID | Employee | Important
1 | Cashier | 1
2 | Manager | 1
3 | Guard | 0


I need a query to return StoreID and EmID where Employee is important (Important = 1) and the store and employee are not connected. Basically, the result should be:



StoreID | EmId
--------+-------
2 | 2
3 | 1
3 | 2


I have tried joins, outer joins / apply-es, except, cte, temporary tables, but still haven't found the answer.



Can someone help me with the code, or at least point me in the right direction?
Any idea will be very much appreciated.



Thanks.










share|improve this question

























  • You can do this by using CROSS JOIN and LEFT JOIN. Check my answer below

    – Thilina Nakkawita
    Nov 14 '18 at 8:57














0












0








0








I have the following tables:



Stores:



StoreID | Name
1 | Store1
2 | Store2
3 | Store3

EmID | StoreID
1 | 1
2 | 1
3 | 1
1 | 2
3 | 2


Employee:



EmID | Employee | Important
1 | Cashier | 1
2 | Manager | 1
3 | Guard | 0


I need a query to return StoreID and EmID where Employee is important (Important = 1) and the store and employee are not connected. Basically, the result should be:



StoreID | EmId
--------+-------
2 | 2
3 | 1
3 | 2


I have tried joins, outer joins / apply-es, except, cte, temporary tables, but still haven't found the answer.



Can someone help me with the code, or at least point me in the right direction?
Any idea will be very much appreciated.



Thanks.










share|improve this question
















I have the following tables:



Stores:



StoreID | Name
1 | Store1
2 | Store2
3 | Store3

EmID | StoreID
1 | 1
2 | 1
3 | 1
1 | 2
3 | 2


Employee:



EmID | Employee | Important
1 | Cashier | 1
2 | Manager | 1
3 | Guard | 0


I need a query to return StoreID and EmID where Employee is important (Important = 1) and the store and employee are not connected. Basically, the result should be:



StoreID | EmId
--------+-------
2 | 2
3 | 1
3 | 2


I have tried joins, outer joins / apply-es, except, cte, temporary tables, but still haven't found the answer.



Can someone help me with the code, or at least point me in the right direction?
Any idea will be very much appreciated.



Thanks.







sql-server






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 14 '18 at 9:24









marc_s

575k12811101257




575k12811101257










asked Nov 14 '18 at 8:24









Roman ClaudiuRoman Claudiu

13




13













  • You can do this by using CROSS JOIN and LEFT JOIN. Check my answer below

    – Thilina Nakkawita
    Nov 14 '18 at 8:57



















  • You can do this by using CROSS JOIN and LEFT JOIN. Check my answer below

    – Thilina Nakkawita
    Nov 14 '18 at 8:57

















You can do this by using CROSS JOIN and LEFT JOIN. Check my answer below

– Thilina Nakkawita
Nov 14 '18 at 8:57





You can do this by using CROSS JOIN and LEFT JOIN. Check my answer below

– Thilina Nakkawita
Nov 14 '18 at 8:57












3 Answers
3






active

oldest

votes


















0














You use a cross join to get the set of all possible employee/store combinations, and a left join to then remove the combinations that exist in the join table1:



declare @Stores table (StoreID int, Name char(6))
insert into @Stores (StoreID,Name) values
(1,'Store1'),
(2,'Store2'),
(3,'Store3')

declare @Employees table (EmID int, Employee varchar(8), Important bit)
insert into @Employees (EmID,Employee,Important) values
(1,'Cashier',1),
(2,'Manager',1),
(3,'Guard' ,0)

declare @Staffing table (EmID int, StoreID int)
insert into @Staffing (EmID,StoreID) values
(1,1),
(2,1),
(3,1),
(1,2),
(3,2)

select
*
from
@Stores s
cross join
@Employees e
left join
@Staffing st
on
s.StoreID = st.StoreID and
e.EmID = st.EmID
where
e.Important = 1 and
st.EmID is null


Results:



StoreID     Name   EmID        Employee Important EmID        StoreID
----------- ------ ----------- -------- --------- ----------- -----------
3 Store3 1 Cashier 1 NULL NULL
2 Store2 2 Manager 1 NULL NULL
3 Store3 2 Manager 1 NULL NULL




1The one I've named Staffing and you didn't name in the question. Note also (for future questions) that my presentation of the sample data takes up approximately as much space as yours in the question, provides the data types, and is a runnable script.






share|improve this answer
























  • that's exactly what i needed. i have been racking my brain for 3 days now. thanks a lot :)

    – Roman Claudiu
    Nov 14 '18 at 9:09



















0














Please use Cross join followed by Left join and filter on IMP and StoreID null.



    create table #Stores
(storeID int, Name varchar(100))

create table #ES
(empid int,storeID int)

create table #E
(eid int,employee varchar(100), imp int)

insert into #stores values(
1,'Store1'),
(2,'Store2'),
(3,'Store3')

insert into #ES values(
1,1),(2,1),(3,1),(1,2),(3,2)

insert into #E values
(1,'Cashier',1),
(2,'Manager', 1),
(3,'Guard',0)

select * from #Stores
select * from #ES
select * from #E

select #stores.storeid,#E.eid from #Stores
cross join #E
LEFT join #ES
on #ES.storeid = #Stores.storeid
and #E.eid = #ES.empid
where #E.imp = 1
and #ES.storeID is null


enter image description here






share|improve this answer































    0














    Try this query.



    I assumed the table name of the "Employee" is dbo.Employee and table name of "Stores" is dbo.Stores and the intermediate table is "dbo.EmpStore"



    SELECT S.StoreID, E.EmID
    FROM dbo.Stores S
    CROSS JOIN dbo.Employees E
    LEFT JOIN dbo.EmpStore ES ON ES.EmID = E.EmID AND ES.StoreID = S.StoreID
    WHERE E.Important=1 AND ES.EmID IS NULL





    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%2f53295777%2fsql-server-except-with-results-from-both-datasets%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














      You use a cross join to get the set of all possible employee/store combinations, and a left join to then remove the combinations that exist in the join table1:



      declare @Stores table (StoreID int, Name char(6))
      insert into @Stores (StoreID,Name) values
      (1,'Store1'),
      (2,'Store2'),
      (3,'Store3')

      declare @Employees table (EmID int, Employee varchar(8), Important bit)
      insert into @Employees (EmID,Employee,Important) values
      (1,'Cashier',1),
      (2,'Manager',1),
      (3,'Guard' ,0)

      declare @Staffing table (EmID int, StoreID int)
      insert into @Staffing (EmID,StoreID) values
      (1,1),
      (2,1),
      (3,1),
      (1,2),
      (3,2)

      select
      *
      from
      @Stores s
      cross join
      @Employees e
      left join
      @Staffing st
      on
      s.StoreID = st.StoreID and
      e.EmID = st.EmID
      where
      e.Important = 1 and
      st.EmID is null


      Results:



      StoreID     Name   EmID        Employee Important EmID        StoreID
      ----------- ------ ----------- -------- --------- ----------- -----------
      3 Store3 1 Cashier 1 NULL NULL
      2 Store2 2 Manager 1 NULL NULL
      3 Store3 2 Manager 1 NULL NULL




      1The one I've named Staffing and you didn't name in the question. Note also (for future questions) that my presentation of the sample data takes up approximately as much space as yours in the question, provides the data types, and is a runnable script.






      share|improve this answer
























      • that's exactly what i needed. i have been racking my brain for 3 days now. thanks a lot :)

        – Roman Claudiu
        Nov 14 '18 at 9:09
















      0














      You use a cross join to get the set of all possible employee/store combinations, and a left join to then remove the combinations that exist in the join table1:



      declare @Stores table (StoreID int, Name char(6))
      insert into @Stores (StoreID,Name) values
      (1,'Store1'),
      (2,'Store2'),
      (3,'Store3')

      declare @Employees table (EmID int, Employee varchar(8), Important bit)
      insert into @Employees (EmID,Employee,Important) values
      (1,'Cashier',1),
      (2,'Manager',1),
      (3,'Guard' ,0)

      declare @Staffing table (EmID int, StoreID int)
      insert into @Staffing (EmID,StoreID) values
      (1,1),
      (2,1),
      (3,1),
      (1,2),
      (3,2)

      select
      *
      from
      @Stores s
      cross join
      @Employees e
      left join
      @Staffing st
      on
      s.StoreID = st.StoreID and
      e.EmID = st.EmID
      where
      e.Important = 1 and
      st.EmID is null


      Results:



      StoreID     Name   EmID        Employee Important EmID        StoreID
      ----------- ------ ----------- -------- --------- ----------- -----------
      3 Store3 1 Cashier 1 NULL NULL
      2 Store2 2 Manager 1 NULL NULL
      3 Store3 2 Manager 1 NULL NULL




      1The one I've named Staffing and you didn't name in the question. Note also (for future questions) that my presentation of the sample data takes up approximately as much space as yours in the question, provides the data types, and is a runnable script.






      share|improve this answer
























      • that's exactly what i needed. i have been racking my brain for 3 days now. thanks a lot :)

        – Roman Claudiu
        Nov 14 '18 at 9:09














      0












      0








      0







      You use a cross join to get the set of all possible employee/store combinations, and a left join to then remove the combinations that exist in the join table1:



      declare @Stores table (StoreID int, Name char(6))
      insert into @Stores (StoreID,Name) values
      (1,'Store1'),
      (2,'Store2'),
      (3,'Store3')

      declare @Employees table (EmID int, Employee varchar(8), Important bit)
      insert into @Employees (EmID,Employee,Important) values
      (1,'Cashier',1),
      (2,'Manager',1),
      (3,'Guard' ,0)

      declare @Staffing table (EmID int, StoreID int)
      insert into @Staffing (EmID,StoreID) values
      (1,1),
      (2,1),
      (3,1),
      (1,2),
      (3,2)

      select
      *
      from
      @Stores s
      cross join
      @Employees e
      left join
      @Staffing st
      on
      s.StoreID = st.StoreID and
      e.EmID = st.EmID
      where
      e.Important = 1 and
      st.EmID is null


      Results:



      StoreID     Name   EmID        Employee Important EmID        StoreID
      ----------- ------ ----------- -------- --------- ----------- -----------
      3 Store3 1 Cashier 1 NULL NULL
      2 Store2 2 Manager 1 NULL NULL
      3 Store3 2 Manager 1 NULL NULL




      1The one I've named Staffing and you didn't name in the question. Note also (for future questions) that my presentation of the sample data takes up approximately as much space as yours in the question, provides the data types, and is a runnable script.






      share|improve this answer













      You use a cross join to get the set of all possible employee/store combinations, and a left join to then remove the combinations that exist in the join table1:



      declare @Stores table (StoreID int, Name char(6))
      insert into @Stores (StoreID,Name) values
      (1,'Store1'),
      (2,'Store2'),
      (3,'Store3')

      declare @Employees table (EmID int, Employee varchar(8), Important bit)
      insert into @Employees (EmID,Employee,Important) values
      (1,'Cashier',1),
      (2,'Manager',1),
      (3,'Guard' ,0)

      declare @Staffing table (EmID int, StoreID int)
      insert into @Staffing (EmID,StoreID) values
      (1,1),
      (2,1),
      (3,1),
      (1,2),
      (3,2)

      select
      *
      from
      @Stores s
      cross join
      @Employees e
      left join
      @Staffing st
      on
      s.StoreID = st.StoreID and
      e.EmID = st.EmID
      where
      e.Important = 1 and
      st.EmID is null


      Results:



      StoreID     Name   EmID        Employee Important EmID        StoreID
      ----------- ------ ----------- -------- --------- ----------- -----------
      3 Store3 1 Cashier 1 NULL NULL
      2 Store2 2 Manager 1 NULL NULL
      3 Store3 2 Manager 1 NULL NULL




      1The one I've named Staffing and you didn't name in the question. Note also (for future questions) that my presentation of the sample data takes up approximately as much space as yours in the question, provides the data types, and is a runnable script.







      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered Nov 14 '18 at 8:48









      Damien_The_UnbelieverDamien_The_Unbeliever

      194k17248335




      194k17248335













      • that's exactly what i needed. i have been racking my brain for 3 days now. thanks a lot :)

        – Roman Claudiu
        Nov 14 '18 at 9:09



















      • that's exactly what i needed. i have been racking my brain for 3 days now. thanks a lot :)

        – Roman Claudiu
        Nov 14 '18 at 9:09

















      that's exactly what i needed. i have been racking my brain for 3 days now. thanks a lot :)

      – Roman Claudiu
      Nov 14 '18 at 9:09





      that's exactly what i needed. i have been racking my brain for 3 days now. thanks a lot :)

      – Roman Claudiu
      Nov 14 '18 at 9:09













      0














      Please use Cross join followed by Left join and filter on IMP and StoreID null.



          create table #Stores
      (storeID int, Name varchar(100))

      create table #ES
      (empid int,storeID int)

      create table #E
      (eid int,employee varchar(100), imp int)

      insert into #stores values(
      1,'Store1'),
      (2,'Store2'),
      (3,'Store3')

      insert into #ES values(
      1,1),(2,1),(3,1),(1,2),(3,2)

      insert into #E values
      (1,'Cashier',1),
      (2,'Manager', 1),
      (3,'Guard',0)

      select * from #Stores
      select * from #ES
      select * from #E

      select #stores.storeid,#E.eid from #Stores
      cross join #E
      LEFT join #ES
      on #ES.storeid = #Stores.storeid
      and #E.eid = #ES.empid
      where #E.imp = 1
      and #ES.storeID is null


      enter image description here






      share|improve this answer




























        0














        Please use Cross join followed by Left join and filter on IMP and StoreID null.



            create table #Stores
        (storeID int, Name varchar(100))

        create table #ES
        (empid int,storeID int)

        create table #E
        (eid int,employee varchar(100), imp int)

        insert into #stores values(
        1,'Store1'),
        (2,'Store2'),
        (3,'Store3')

        insert into #ES values(
        1,1),(2,1),(3,1),(1,2),(3,2)

        insert into #E values
        (1,'Cashier',1),
        (2,'Manager', 1),
        (3,'Guard',0)

        select * from #Stores
        select * from #ES
        select * from #E

        select #stores.storeid,#E.eid from #Stores
        cross join #E
        LEFT join #ES
        on #ES.storeid = #Stores.storeid
        and #E.eid = #ES.empid
        where #E.imp = 1
        and #ES.storeID is null


        enter image description here






        share|improve this answer


























          0












          0








          0







          Please use Cross join followed by Left join and filter on IMP and StoreID null.



              create table #Stores
          (storeID int, Name varchar(100))

          create table #ES
          (empid int,storeID int)

          create table #E
          (eid int,employee varchar(100), imp int)

          insert into #stores values(
          1,'Store1'),
          (2,'Store2'),
          (3,'Store3')

          insert into #ES values(
          1,1),(2,1),(3,1),(1,2),(3,2)

          insert into #E values
          (1,'Cashier',1),
          (2,'Manager', 1),
          (3,'Guard',0)

          select * from #Stores
          select * from #ES
          select * from #E

          select #stores.storeid,#E.eid from #Stores
          cross join #E
          LEFT join #ES
          on #ES.storeid = #Stores.storeid
          and #E.eid = #ES.empid
          where #E.imp = 1
          and #ES.storeID is null


          enter image description here






          share|improve this answer













          Please use Cross join followed by Left join and filter on IMP and StoreID null.



              create table #Stores
          (storeID int, Name varchar(100))

          create table #ES
          (empid int,storeID int)

          create table #E
          (eid int,employee varchar(100), imp int)

          insert into #stores values(
          1,'Store1'),
          (2,'Store2'),
          (3,'Store3')

          insert into #ES values(
          1,1),(2,1),(3,1),(1,2),(3,2)

          insert into #E values
          (1,'Cashier',1),
          (2,'Manager', 1),
          (3,'Guard',0)

          select * from #Stores
          select * from #ES
          select * from #E

          select #stores.storeid,#E.eid from #Stores
          cross join #E
          LEFT join #ES
          on #ES.storeid = #Stores.storeid
          and #E.eid = #ES.empid
          where #E.imp = 1
          and #ES.storeID is null


          enter image description here







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 14 '18 at 8:52









          WhoamIWhoamI

          157119




          157119























              0














              Try this query.



              I assumed the table name of the "Employee" is dbo.Employee and table name of "Stores" is dbo.Stores and the intermediate table is "dbo.EmpStore"



              SELECT S.StoreID, E.EmID
              FROM dbo.Stores S
              CROSS JOIN dbo.Employees E
              LEFT JOIN dbo.EmpStore ES ON ES.EmID = E.EmID AND ES.StoreID = S.StoreID
              WHERE E.Important=1 AND ES.EmID IS NULL





              share|improve this answer






























                0














                Try this query.



                I assumed the table name of the "Employee" is dbo.Employee and table name of "Stores" is dbo.Stores and the intermediate table is "dbo.EmpStore"



                SELECT S.StoreID, E.EmID
                FROM dbo.Stores S
                CROSS JOIN dbo.Employees E
                LEFT JOIN dbo.EmpStore ES ON ES.EmID = E.EmID AND ES.StoreID = S.StoreID
                WHERE E.Important=1 AND ES.EmID IS NULL





                share|improve this answer




























                  0












                  0








                  0







                  Try this query.



                  I assumed the table name of the "Employee" is dbo.Employee and table name of "Stores" is dbo.Stores and the intermediate table is "dbo.EmpStore"



                  SELECT S.StoreID, E.EmID
                  FROM dbo.Stores S
                  CROSS JOIN dbo.Employees E
                  LEFT JOIN dbo.EmpStore ES ON ES.EmID = E.EmID AND ES.StoreID = S.StoreID
                  WHERE E.Important=1 AND ES.EmID IS NULL





                  share|improve this answer















                  Try this query.



                  I assumed the table name of the "Employee" is dbo.Employee and table name of "Stores" is dbo.Stores and the intermediate table is "dbo.EmpStore"



                  SELECT S.StoreID, E.EmID
                  FROM dbo.Stores S
                  CROSS JOIN dbo.Employees E
                  LEFT JOIN dbo.EmpStore ES ON ES.EmID = E.EmID AND ES.StoreID = S.StoreID
                  WHERE E.Important=1 AND ES.EmID IS NULL






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Nov 14 '18 at 8:56

























                  answered Nov 14 '18 at 8:51









                  Thilina NakkawitaThilina Nakkawita

                  9211228




                  9211228






























                      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%2f53295777%2fsql-server-except-with-results-from-both-datasets%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







                      Popular posts from this blog

                      Xamarin.iOS Cant Deploy on Iphone

                      Glorious Revolution

                      Dulmage-Mendelsohn matrix decomposition in Python