alias in case when sqlserver - sql-server

I wrote a trigger to update status to Order from OrderDetails status:
BEGIN
/*
Order Status:
Pending = 0,
Processing = 1,
Proceeded = 2,
Completed = 3,
Cancelled = 4,
Order Detail Status:
Pending = 0,
Processing = 1,
Proceeded = 2,
Emailed = 3,
Ordered = 4,
Cancelled = 5
*/
IF (UPDATE([Status]))
BEGIN
UPDATE [Order]
SET [Status] =
CASE (SELECT MIN(od.[Status]) FROM OrderDetail od WHERE od.OrderId = i.OrderId)
WHEN 5 THEN 4
WHEN 4 THEN 3
WHEN 3 THEN 2
WHEN 2 THEN 2
WHEN 1 THEN 1
WHEN 0 THEN 0
END
FROM INSERTED i
WHERE [Order].Id = i.OrderId
END
END
You can see, WHEN OrderDetailStatus = 2 OR 3 THEN OrderStatus = 2, otherwise OrderStatus = OrderDetailStatus. For now, I have to list the values of status.
So, is it possible to create a alias for value statement, like this:
SET [Status] =
CASE (SELECT MIN(od.[Status]) FROM OrderDetail od WHERE od.OrderId = i.OrderId) AS val
WHEN 3 THEN 2
ELSE val
END
FROM INSERTED i
WHERE [Order].Id = i.OrderId

The only way I can think to "shorten" this would be:
UPDATE O
SET [Status] = CASE WHEN od.[Status] BETWEEN 3 AND 5 THEN od.[Status] - 1 ELSE od.[Status] END
FROM [Order] O
JOIN INSERTED i ON O.Id = i.OrderId
CROSS APPLY (SELECT MIN(od.[Status]) AS [Status]
FROM OrderDetail ca
WHERE ca.OrderId = i.OrderId) od;
On a different note, you should really avoid using reserved (or even key) words for object names. ORDER is a reserved word in SQL Server, so should really not be used. Status is a key word, so can be, but should also be avoided.

Related

Stored Procedure - How to Ignore a Join when #packageType = 1

I want to change the left join to inner join, but for me to do that,
I want the PACKAGEDETAILS.MenuID = MENU.ID join to happen only if the #packageType = 2, else I want my stored procedure to ignore the join
I am new to stored procedures and SQL, I tried using case when, but I failed, I tried if then, still didn't achieve what I wanted.
set #slot = 5;
set #numberofattendees = 100;
set #foodtype = 0;
set #packagetype = 1;
select * FROM PROPERTY
JOIN PACKAGEDETAILS ON PACKAGEDETAILS.ID =
(SELECT
PACKAGEDETAILS.ID
FROM
PACKAGEDETAILS
`````````````````````````````````````````````````````
LEFT JOIN MENU ON PACKAGEDETAILS.MenuID = MENU.ID AND -- i want this join to happen only if the #packageType = 2
MENU.IsActive = 1 AND
MENU.IsDeleted = 0 AND
(MENU.FoodTypeID = 0 OR #FoodType = 0)
`````````````````````````````````````````````````````
JOIN PACKAGEAPPLICABILITY ON PACKAGEDETAILS.ID = PACKAGEAPPLICABILITY.packagedetailsid
WHERE
PACKAGEAPPLICABILITY.IsActive = 1 AND
PACKAGEAPPLICABILITY.IsDeleted = 0
ORDER BY
PACKAGEDETAILS.CostPrice ASC LIMIT 1
)
Since there wont be any menu for packageType 1, I want my stored procedure to ignore the join if #packageType = 1 and only work when #packageType = 2.
You are trying to pack 2 different queries into 1. In general, that is not a good idea in SQL, as it makes the query optimizer work much harder. You will be better off with either writing 2 separate procedures, or within the same procedure, write 2 separate queries and use IF conditional execution to decide which query to execute:
IF Packagetype = 2
select * FROM PROPERTY
JOIN PACKAGEDETAILS ON PACKAGEDETAILS.ID =
(SELECT
PACKAGEDETAILS.ID
FROM
PACKAGEDETAILS
`````````````````````````````````````````````````````
LEFT JOIN MENU ON PACKAGEDETAILS.MenuID = MENU.ID AND -- i want this join to happen only if the #packageType = 2
MENU.IsActive = 1 AND
MENU.IsDeleted = 0 AND
(MENU.FoodTypeID = 0 OR #FoodType = 0)
`````````````````````````````````````````````````````
JOIN PACKAGEAPPLICABILITY ON PACKAGEDETAILS.ID = PACKAGEAPPLICABILITY.packagedetailsid
WHERE
PACKAGEAPPLICABILITY.IsActive = 1 AND
PACKAGEAPPLICABILITY.IsDeleted = 0
ORDER BY
PACKAGEDETAILS.CostPrice ASC LIMIT 1
)
ELSE
select * FROM PROPERTY
JOIN PACKAGEDETAILS ON PACKAGEDETAILS.ID =
(SELECT
PACKAGEDETAILS.ID
FROM
PACKAGEDETAILS
JOIN PACKAGEAPPLICABILITY ON PACKAGEDETAILS.ID = PACKAGEAPPLICABILITY.packagedetailsid
WHERE
PACKAGEAPPLICABILITY.IsActive = 1 AND
PACKAGEAPPLICABILITY.IsDeleted = 0
ORDER BY
PACKAGEDETAILS.CostPrice ASC LIMIT 1
)
Define a variable and construct your query by setting the variable according to your conditions. When you create the query execute it with exec command.
Here is an example.

Case Statement On Two Conditions

Can i add these both together to work as one, the user can select valid for country 1 or 2 and BOTH so i need these to work together
if possible
and when user selects both i need it to show both measurements
I CANNOT CREATE A NEW TABLE so i need essentially column that will populate based on what country and unit price base will be sufficient
,CASE
WHEN bd.Validforcountry = 1 and BD.UnitpriceBase = 1
THEN '100 ml'
WHEN bd.Validforcountry = 1 and BD.UnitpriceBase = 2
THEN '1 l'
WHEN bd.Validforcountry = 1 and BD.UnitpriceBase = 3
THEN '100 g'
WHEN bd.Validforcountry = 1 and BD.UnitpriceBase = 4
THEN '1 Kg'
WHEN bd.Validforcountry = 1 and BD.UnitpriceBase = 5
THEN '750 ml'
ELSE BD.UnitpriceBase
END AS 'Unit price Declaration'
,CASE
WHEN bd.Validforcountry = 2 and BD.UnitpriceBase = 1
THEN '100 ml'
WHEN bd.Validforcountry = 2 and BD.UnitpriceBase = 2
THEN '1 l'
WHEN bd.Validforcountry = 2 and BD.UnitpriceBase = 3
THEN '100 g'
WHEN bd.Validforcountry = 2 and BD.UnitpriceBase = 4
THEN '1 Kg'
WHEN bd.Validforcountry = 2 and BD.UnitpriceBase = 5
THEN '750 ml'
ELSE BD.UnitpriceBase
END AS 'Unit price Declaration'
Instead of creating complex CASE WHEN, just create a new table, so you can select the correct value with a simple JOIN. Something like this:
CREATE TABLE UnitPriceDeclaration
(
Country int,
UnitPriceBase int,
UnitPriceDeclaration varchar(20),
PRIMARY KEY (Country, UnitPriceBase)
);
This way, you can write your query like this (dummy joins, I don't know anything about your other tables):
SELECT t1.someField,
t2.someOtherField,
t1.UnitPriceBase,
t2.Country,
upd.UnitPriceDeclaration
FROM oneTable t1,
INNER JOIN anotherTable t2 ON ...
INNER JOIN UnitPriceDeclaration upd ON upd.Country = t2.Country AND upd.UnitPriceBase = t1.UnitPriceBase -- maybe LEFT JOIN
WHERE...
This allows you to keep flexibility and add/change as many countries, UPB or UPD as you want, without anything to change other than data. Using CASE WHEN as you do, you would have to change your code each time something changes (potentially in more than one place).
Your edit advocates for this solution. See all those repeated values ?
So let's say you want to display two UPD, one for UK and one for IRE. You just have to do something like this:
SELECT t1.someField,
t2.someOtherField,
t1.UnitPriceBase,
t2.Country,
upduk.UnitPriceDeclaration as UPD_UK,
updire.UnitPriceDeclaration as UPD_IRE
FROM oneTable t1,
INNER JOIN UnitPriceDeclaration upduk ON upd.UnitPriceBase = t1.UnitPriceBase AND upd.Country = 1
INNER JOIN UnitPriceDeclaration updire ON upd.UnitPriceBase = t1.UnitPriceBase AND upd.Country = 2
WHERE...

Two sorted subqueries into one result

So I have two subqueries that return the same columns from the same table
Query #1:
SELECT E.Id,E.Title,E.LocationId,P.LocationId,E.DepartmentId,P.DepartmentId,E.DateCreated,E.IsActive,E.IsHotJob,E.RequisitionId,E.RequisitionIdString,E.RewardSettingId,E.EmploymentOpportunityStatusId
FROM EmploymentOpportunities E, Profiles P
WHERE E.EmploymentOpportunityStatusId = 9 AND E.IsActive = 1 AND E.IsHotjob = 1
AND P.Id = 'C5F07EBB-CE81-4133-A462-241A5F84D418' AND (P.DepartmentId != E.DepartmentId AND P.LocationId != E.LocationId)
ORDER BY E.DateCreated DESC
Query #2:
SELECT E.Id,E.Title,E.LocationId,P.LocationId,E.DepartmentId,P.DepartmentId,E.DateCreated,E.IsActive,E.IsHotJob,E.RequisitionId,E.RequisitionIdString,E.RewardSettingId,E.EmploymentOpportunityStatusId
FROM EmploymentOpportunities E, Profiles P
WHERE E.EmploymentOpportunityStatusId = 9 AND E.IsActive = 1 AND E.IsHotjob = 0 AND
P.Id = 'C5F07EBB-CE81-4133-A462-241A5F84D418' AND (P.DepartmentId = E.DepartmentId OR P.LocationId = E.LocationId)
ORDER BY E.DateCreated DESC
I want this two queries combines into one but preserve the order they have, so somehow stack Query #1 onto Query #2.
Is this possible?
SELECT 1 SetNumber, E.Id,E.Title,E.LocationId,P.LocationId,E.DepartmentId,
P.DepartmentId,E.DateCreated,E.IsActive,E.IsHotJob,E.RequisitionId,
E.RequisitionIdString,E.RewardSettingId,E.EmploymentOpportunityStatusId
FROM EmploymentOpportunities E, Profiles P
WHERE E.EmploymentOpportunityStatusId = 9 AND E.IsActive = 1
AND E.IsHotjob = 1 P.Id = 'C5F07EBB-CE81-4133-A462-241A5F84D418'
AND (P.DepartmentId != E.DepartmentId AND P.LocationId != E.LocationId)
union all
SELECT 2, E.Id,E.Title,E.LocationId,P.LocationId,E.DepartmentId,P.DepartmentId,
E.DateCreated,E.IsActive,E.IsHotJob,E.RequisitionId,E.RequisitionIdString,
E.RewardSettingId,E.EmploymentOpportunityStatusId
FROM EmploymentOpportunities E, Profiles P
WHERE E.EmploymentOpportunityStatusId = 9 AND E.IsActive = 1
AND E.IsHotjob = 0 AND P.Id = 'C5F07EBB-CE81-4133-A462-241A5F84D418'
AND (P.DepartmentId = E.DepartmentId OR P.LocationId = E.LocationId)
ORDER BY SetNumber, DateCreated desc
Just use UNION ALL
SELECT * FROM
(
Your Query1
UNION ALL // do not use order by here
Your Query2
) AS someName
ORDER BY yourColumn DESC
You can also use UNION - but it will filter out duplicates if any.

Sql query to create teams

I need a query to assign teams to a series of users. Data looks like this:
UserId Category Team
1 A null
2 A null
3 B null
4 B null
5 A null
6 B null
8 A null
9 B null
11 B null
Teams should be created by sorting by userid and the first userid becomes the team number and the consecutive A's are part of that team as are the B's that follow. The first A after the Bs starts a new team. There will always be at least one A and one B. So after the update, that data should look like this:
UserId Category Team
1 A 1
2 A 1
3 B 1
4 B 1
5 A 5
6 B 5
8 A 8
9 B 8
11 B 8
EDIT:
Need to add that the user id's will not always increment by 1. I edited the example data to show what I mean. Also, the team ID doesn't strictly have to be the id of the first user, as long as they end up grouped properly. For example, users 1 - 4 could all be on team '1', users 5 and 6 on team '2' and users 8,9 and 11 on team '3'
First you could label each row with an increasing number. Then you can use a left join to find the previous user. If the previous user has category 'B', and the current one category 'A', that means the start of a new team. The team number is then the last UserId that started a new team before the current UserId.
Using SQL Server 2008 syntax:
; with numbered as
(
select row_number() over (order by UserId) rn
, *
from Table1
)
, changes as
(
select cur.UserId
, case
when prev.Category = 'B' and cur.Category = 'A' then cur.UserId
when prev.Category is null then cur.UserId
end as Team
from numbered cur
left join
numbered prev
on cur.rn = prev.rn + 1
)
update t1
set Team = team.Team
from Table1 t1
outer apply
(
select top 1 c.Team
from changes c
where c.UserId <= t1.UserId
and c.Team is not null
order by
c.UserId desc
) as team;
Example at SQL Fiddle.
You can do this with a recursive CTE:
with userCTE as
(
select UserId
, Category
, Team = UserId
from users where UserId = 1
union all
select users.UserId
, users.Category
, Team = case when users.Category = 'A' and userCTE.Category = 'B' then users.UserId else userCTE.Team end
from userCTE
inner join users on users.UserId = userCTE.UserId + 1
)
update users
set Team = userCTE.Team
from users
inner join userCTE on users.UserId = userCTE.UserId
option (maxrecursion 0)
SQL Fiddle demo.
Edit:
You can update the CTE to get this to go:
with userOrder as
(
select *
, userRank = row_number() over (order by userId)
from users
)
, userCTE as
(
select UserId
, Category
, Team = UserId
, userRank
from userOrder where UserId = (select min(UserId) from users)
union all
select users.UserId
, users.Category
, Team = case when users.Category = 'A' and userCTE.Category = 'B' then users.UserId else userCTE.Team end
, users.userRank
from userCTE
inner join userOrder users on users.userRank = userCTE.userRank + 1
)
update users
set Team = userCTE.Team
from users
inner join userCTE on users.UserId = userCTE.UserId
option (maxrecursion 0)
SQL Fiddle demo.
Edit:
For larger datasets you'll need to add the maxrecursion query hint; I've edited the previous queries to show this. From Books Online:
Specifies the maximum number of recursions allowed for this query.
number is a nonnegative integer between 0 and 32767. When 0 is
specified, no limit is applied.
In this case I've set it to 0, i.e. not limit on recursion.
Query Hints.
I actually ended up going with the following. It finished on all 3 million+ rows in a half an hour.
declare #userid int
declare #team int
declare #category char(1)
declare #lastcategory char(1)
set #userid = 1
set #lastcategory='B'
set #team=0
while #userid is not null
begin
select #category = category from users where userid = #userid
if #category = 'A' and #lastcategory = 'B'
begin
set #team = #userid
end
update users set team = #team where userid = #userid
set #lastcategory = #category
select #userid = MIN(userid) from users where userid > #userid
End

SQL query - need to exclude if Requirement NOT met, and exclude if Disqualifier IS met

I have a feeling once i see the solution i'll slap my forehead, but right now I'm not seeing it.
I have a lookup table, say TableB, which looks like this. All fields are INT except the last two which are BOOL.
ID, TableA_ID, Value, Required, Disqualifies
I have a list of TableA_Id values (1, 2, 3 ) etc
For each record in this table, either Required can be true or disqualified can be true - they cant both be true at the same time. They can both be false or null though. There can be duplicate values of TableA_Id but there should never be duplicates of TableA_Id and Value
If required is true for any of those TableA_ID values, and none of those values are in my list, return no records. If none of the values are marked as required (required = 0 or null) then return records UNLESS any of the values are marked as Disqualifies and are in the list, in which case i want to return no records.
So - if a field is required and i dont have it, dont return any records. If a field is marked as disqualified and i have it, don't return any records. Only return a record if either i have a required value or don't have a disqualified value or there are no required values.
I hope I explained myself clearly.
Thanks in advance for pointing me in the right direction.
As an example of what my records might look like:
ID TableA_ID Value Required Disqualifies
-- --------- ----- -------- ------------
1 123 1 True False
2 123 2 True False
3 123 3 False False
4 123 4 False True
5 456 1 False True
6 456 2 False False
Given this set of sample data, if we're working with TableA_Id 123 and my list of values is lets say 1 and 3, i would get data returned because i have a required value and dont have any disqualified values. If my list of values were just 3, i'd get no records since i'm missing of the Required values. If my list of values were 1 and 4, i'd get no records because 4 is marked as disqualified.
Now if we're working with TableA_Id 456, the only list of values that would return any records is 2.
Maybe i should post the whole SQL query - i was trying to keep this short to make it easier for everyone, but it looks like maybe that's not working so well.
Here is the full dynamically generated query. The bit i am working on now is the 2nd line from the bottom. To equate this to my example, t.id would be TableA_ID, Value would be PDT_ID.
SELECT DISTINCT t.ID, t.BriefTitle, stat.Status, lstat.Status AS LocationStatus, st.SType, t.LAgency, l.City, state.StateCode
,( SELECT TOP 1 UserID
FROM TRecruiter
WHERE TrialID = t.ID AND Lead = 1 ), l.ID as LocationID
, l.WebBased
FROM Trial t
INNER JOIN Location l ON t.ID = l.TrialID
FULL JOIN pdt on t.ID = pdt.trialid
FULL JOIN pdm on t.ID = pdm.TrialID
FULL JOIN s on t.ID = s.TrialID
FULL JOIN hy on t.ID = hy.TrialID
FULL JOIN ta on t.ID = ta.TrialID
FULL JOIN stt on t.ID = stt.TrialID
FULL JOIN [Status] stat ON t.StatusID = stat.ID
FULL JOIN st ON t.StudyTypeID = st.ID
FULL JOIN State state ON l.StateID = state.ID
FULL JOIN [Status] lstat ON l.StatusID = lstat.ID
FULL JOIN ts ON t.ID = ts.TrialID
FULL JOIN tpdm ON t.ID = tpdm.TrialID
WHERE ((t.ID IS NOT NULL)
AND (EligibleHealthyVolunteers IS NULL OR EligibleHealthyVolunteers = 1 OR (0 = 0 AND EligibleHealthyVolunteers = 0))
AND (eligiblegenderid is null OR eligiblegenderid = 1 OR eligiblegenderid = 3)
AND ((EligibleMinAge <= 28 AND EligibleMaxAge >= 28) OR (EligibleMinAge <= 28 AND EligibleMaxAge is null) OR (EligibleMinAge IS NULL AND EligibleMaxAge >= 28))
AND (HYID = 6 AND (hy.Disqualify = 0 OR hy.Disqualify IS NULL AND NOT EXISTS (SELECT * FROM hy WHERE t.id = hy.TrialID AND hy.Req =1)) OR HYID = 6 AND hy.req = 1)
AND (PDT_ID IN (1) AND ( pdt.Disqualify = 0 OR pdt.Disqualify IS NULL AND NOT EXISTS (select * from pdt where t.id = pdt.TrialID AND pdt.Req = 1)) OR PDT_ID IN (1) AND (pdt.Req = 1 AND (pdt.Disqualify = 0 or pdt.Disqualify is null )))
) AND ((3959 * acos(cos(radians(34.18)) * cos(radians(l.Latitude)) * cos(radians(l.Longitude) - radians(-118.46)) + sin(radians(34.18)) * sin(radians(l.Latitude)))) <= 300 OR l.Latitude IS NULL) AND t.IsPublished = 1 AND (t.StatusID = 1 OR t.StatusID = 2)
I've changed/shortened some table names just for security/privacy reasons.
Edit:
I think i am close to getting this working, but I'm getting tripped up on the logic again.
I have the following bit of sql:
AND ( exists (SELECT * FROM pdt WHERE Req = 1 AND trialid = t.id AND pdT_ID IN (2) ) AND EXISTS (SELECT * FROM pdt WHERE Req = 1 AND trialid = t.id ) )
I'm not sure how to structure this. Those two exists statement should make the whole thing true in the following combination:
True & False
True & True
False & False
If it's False & True, then the whole thing is false. In other words if there is a Req =1 AND the PDT_ID that is marked as Req=1 is not in our list (in the example above the list just contains '2') then return false.
EDIT:
I think i finally got it.
AND NOT EXISTS (SELECT * FROM pdt WHERE Disqualify = 1 AND trialid = t.id AND PDT_ID IN (2) )
AND NOT ( NOT exists (SELECT * FROM pdt WHERE Req = 1 AND trialid = t.id AND PDT_ID IN (2) ) AND EXISTS (SELECT * FROM pdt WHERE Req = 1 AND trialid = t.id ) )
So far this seems to work in testing. Although I'm only working with two values of PDT_ID. If this does resolve my problem, i will come back and give someone the credit for helping me.
SELECT *
FROM TABLEB B
WHERE
(
B.REQUIRED = 1
AND EXISTS
(
SELECT 1
FROM TABLEA A
WHERE A.ID =B.TABLEA_ID
)
)
OR
(
B.REQUIRED != 1
AND B.DISQUALIFIES <> 1
)
OR
(
B.REQUIRED != 1
AND B.DISQUALIFIES = 1
AND EXISTS
(
SELECT 1
FROM TABLEA A
WHERE A.ID =B.TABLEA_ID
)
)
UPDATE - after the EDIT and explanation from OP:
Change the line
FULL JOIN pdt on t.ID = pdt.trialid
To
FULL JOIN (SELECT * FROM pdt BB WHERE
BB.TrialID IN (SELECT AA.ID FROM Trial AA WHERE AA.ID = BB.TrialID) AND
1 > (SELECT COUNT(*) FROM Trial A
LEFT OUTER JOIN pdt B ON B.Req != 1 AND B.Disqualify != 1 AND B.TrialID = A.ID
WHERE B.TrialID IS NULL)) pdt ON t.ID = pdt.TiralID
AND change the line before last from
AND (PDT_ID IN (1) AND ( pdt.Disqualify = 0 OR pdt.Disqualify IS NULL AND NOT EXISTS (select * from pdt where t.id = pdt.TrialID AND pdt.Req = 1)) OR PDT_ID IN (1) AND (pdt.Req = 1 AND (pdt.Disqualify = 0 or pdt.Disqualify is null )))
To
AND PDT_ID IN (1)
(You seem to have found a solution, yet I've decided to share my thoughts about this problem anyway.)
Given you've got a set of TableA IDs, each of which is accompanied by a set of some values, and you want to test the entire row set against this TableB thing using the rules you've set forth, I think the entire checking process might look like this:
Match every pair of TableA.ID and Value against TableB and get aggregate maximums of Required and Disqualifies for every TableA.ID along the way.
Derive a separate list of TableA_ID values with their corresponding maximum values of Required, from TableB. That will be for us to know whether a particular TableA_ID must have a required value at all.
Match the row set obtained at Stage 1 against the derived table (Stage 2) and check the aggregate values:
1) if the actual aggregate Disqualifies for a TableA_ID is 1, discard this TableA_ID set;
2) if a TableA_ID has a match in the Stage 2 derived table and the aggregate maximum of Required that we obtained at Stage 1 doesn't match the maximum Required in the derived table, discard the set as well.
Something tells me that it would be better at this point to move on to some sort of illustration. Here's a sample script, with comments explaining which part of the script implements which part of the description above:
;
WITH
/* this is the row set to be tested and which
is supposed to contain TableA.IDs and Values */
testedRowSet AS (
SELECT
TableA.ID AS TableA_ID,
SomethingElse.TestedValue AS Value,
...
FROM TableA
JOIN SomethingElse ON some_condition
...
),
/* at this point, we are getting the aggregate maximums
of TableB.Required and TableB.Disqualifies for every
TableA_ID in testedRowSet */
aggregated AS (
SELECT
testedRowSet.TableA_ID,
testedRowSet.Value,
...
DoesHaveRequiredValues = MAX(CASE TableB.Required WHEN 1 THEN 1 ELSE 0 END) OVER (PARTITION BY testedRowSet.TableA_ID),
HasDisqualifyingValues = MAX(CASE TableB.Disqualifies WHEN 1 THEN 1 ELSE 0 END) OVER (PARTITION BY testedRowSet.TableA_ID)
FROM testedRowSet
LEFT JOIN TableB ON testedRowSet.TableA_ID = TableB.TableA_ID
AND testedRowSet.Value = TableB.Value
),
/* this row set will let us see whether a particular
TableA_ID must have a required value */
properties AS (
SELECT
TableA_ID,
MustHaveRequiredValues = MAX(CASE Required WHEN 1 THEN 1 ELSE 0 END)
FROM TableB
GROUP BY TableA_ID
),
/* this is where we are actually checking the previously
obtained aggregate values of Required and Disqualifies */
tested AS (
SELECT
aggregated.TableA_ID,
aggregated.Value,
...
FROM aggregated
LEFT JOIN properties ON aggregated.TableA_ID = properties.TableA_ID
WHERE aggregated.HasDisqualifyingValues = 0
AND (properties.TableA_ID IS NULL
OR properties.MustHaveRequiredValues = aggregated.DoesHaveRequiredValues)
)
SELECT * FROM tested

Resources