I'm not sure how to explain this question so let me try with a simplified example.
I have two tables Tickets and TicketEntities:
Tickets
tID | Customer | Val
----|----------|------
1 | Paul | 20
2 | Paul | 10
3 | Peter | 15
4 | Jane | 100
5 | Doe | 400
6 | John | 5
TicketEntities
EntityID | TicketID | Type
---------|-----------|--------
1 | 1 | 1
2 | 1 | 2
3 | 3 | 1
4 | 4 | 1
5 | 5 | 2
6 | 6 | 2
I want to create two views (preferably so if one view is possible):
[Already solved] View to show me Tickets with TicketEntity type 1. My working solution: Desired Result:
tID | Customer | Val | EntityID | Type
-------|-------------|-----|----------|------- 1 | Paul | 20 | 1 | 1 3 | Peter | 15 | 3 | 1 4 | Jane | 100 | 4 | 1
Note: Not actual query/results
SQL
SELECT * FROM Tickets AS t LEFT JOIN TicketEntities AS e ON t.ID=e.TicketID WHERE e.EntityTypeId = 1
View with only Tickets with TicketEntity type 2 but not 1
Desired Result:
tID | Customer | Val | EntityID | Type ------|-------------|-----|----------|------- 5 | Doe | 400 | 5 | 2 6 | John | 5 | 6 | 2
SQL
SELECT * FROM Tickets AS t LEFT JOIN TicketEntities AS e ON t.ID=e.TicketID WHERE e.EntityTypeId = 1 AND NOT EXISTS (SELECT * FROM dbo.Tickets AS t2 INNER JOIN dbo.TicketEntities AS e2 ON t2.Id=e2.Ticket_Id WHERE e2.EntityTypeId = 2)
OR more preferably, the single view:
Desired Result:
tID | Customer | Val | Entity_Type1 | Entity_Type2 -------|-------------|------|---------------|--------------- 1 | Paul | 20 | 1 | 2 2 | Paul | 10 | | 3 | Peter | 15 | 1 | 4 | Jane | 100 | 1 | 5 | Doe | 400 | | 2 6 | John | 5 | | 2
SQL
I'm not sure how to go about it. Self join?
Finally, Improvements to the question are welcome. What's the best way to approach this problem?