I have three fields I want to filter my query by. I want to query even if 1 or 2 of the fields are empty (passing an empty string). I can figure out 1 field, but once I add the other two, I do not get any results. Curly brackets are my form fields that get passed to the query.
IF '{Envelope Size}' <> ''
SELECT Tools.ToolNo,
Tools.[Name]
FROM Tools
LEFT JOIN
(
SELECT AdditionalInfo.OwnerID,
AdditionalInfo.UserDefined3,
AdditionalInfo.UserDefined4,
AdditionalInfo.UserDefined5,
AdditionalInfo.UserDefined10,
AdditionalInfo.UserDefined24
FROM AdditionalInfo
WHERE AdditionalInfo.ModuleID = 35
) AS EnvStyle ON Tools.ToolID = EnvStyle.OwnerID
WHERE EnvStyle.UserDefined24 LIKE '{Envelope Size}';
ELSE
SELECT Tools.ToolNo,
Tools.[Name]
FROM Tools
LEFT JOIN
(
SELECT AdditionalInfo.OwnerID,
AdditionalInfo.UserDefined3,
AdditionalInfo.UserDefined4,
AdditionalInfo.UserDefined5,
AdditionalInfo.UserDefined12
FROM AdditionalInfo
WHERE AdditionalInfo.ModuleID = 35
) AS EnvStyle ON Tools.ToolID = EnvStyle.OwnerID
WHERE EnvStyle.UserDefined3 <> 'Stationery'
AND EnvStyle.UserDefined4 = (CASE WHEN '{Env. Height}' = '' THEN 'NULL' ELSE '{Env. Height}' END)
AND EnvStyle.UserDefined5 = (CASE WHEN '{Env. Width}' = '' THEN 'NULL' ELSE '{Env. Width}' END)
AND EnvStyle.UserDefined12 = (CASE WHEN '{Flap Size}' = '' THEN 'NULL' ELSE '{Flap Size}' END);
I'm not exactly clear on what your data structure is and the curly braces are throwing me off a bit, but maybe something like this might work for you. You could change your filter conditions to use an OR with a CASE to force a match in those cases when the values are blank. Again, I'm not sure of your structure and the below is just following your example, but hopefully this might get you in the right direction.
IF '{Envelope Size}' <> ''
SELECT Tools.ToolNo,
Tools.[Name]
FROM Tools
LEFT JOIN
(
SELECT AdditionalInfo.OwnerID,
AdditionalInfo.UserDefined3,
AdditionalInfo.UserDefined4,
AdditionalInfo.UserDefined5,
AdditionalInfo.UserDefined10,
AdditionalInfo.UserDefined24
FROM AdditionalInfo
WHERE AdditionalInfo.ModuleID = 35
) AS EnvStyle ON Tools.ToolID = EnvStyle.OwnerID
WHERE EnvStyle.UserDefined24 LIKE '{Envelope Size}';
ELSE
SELECT Tools.ToolNo,
Tools.[Name]
FROM Tools
LEFT JOIN
(
SELECT AdditionalInfo.OwnerID,
AdditionalInfo.UserDefined3,
AdditionalInfo.UserDefined4,
AdditionalInfo.UserDefined5,
AdditionalInfo.UserDefined12
FROM AdditionalInfo
WHERE AdditionalInfo.ModuleID = 35
) AS EnvStyle ON Tools.ToolID = EnvStyle.OwnerID
WHERE EnvStyle.UserDefined3 <> 'Stationery'
AND (EnvStyle.UserDefined4 = {Env.Height}
OR 1 = CASE WHEN {Env.Height} = '' THEN 1 ELSE 0 END)
AND (EnvStyle.UserDefined5 = {Env.Width}
OR 1 = CASE WHEN {Env.Width} = '' THEN 1 ELSE 0 END)
AND (EnvStyle.UserDefined12 = {Flap Size}
OR 1 = CASE WHEN {Flap Size} = '' THEN 1 ELSE 0 END);
Related
Needs to create view with below columns. Need to understand how to create view using with clause inside the query.
create
or replace view TEST_RRX.DW_RRX.V_SIL_RRX_PTS_BusinessLocation_Dim(
--ROW_WID,
--ADDRESS_TYPE,
BUSN_LOC_NAME,
BUSN_LOC_NUM,
BUSN_LOC_TYPE,
ST_ADDRESS1,
ST_ADDRESS2,
CITY_NAME,
POSTAL_CODE,
STATE_CODE,
COUNTRY_CODE,
ACTIVE_FLG,
CREATED_BY_WID,
CHANGED_BY_WID,
CREATED_ON_DT,
CHANGED_ON_DT,
AUX1_CHANGED_ON_DT,
AUX2_CHANGED_ON_DT,
AUX3_CHANGED_ON_DT,
AUX4_CHANGED_ON_DT,
SRC_EFF_FROM_DT,
SRC_EFF_TO_DT,
EFFECTIVE_FROM_DT,
EFFECTIVE_TO_DT,
DELETE_FLG,
CURRENT_FLG,
W_INSERT_DT,
W_UPDATE_DT,
DATASOURCE_NUM_ID,
--ETL_PROC_WID,
INTEGRATION_ID,
--TENANT_ID,
--X_CUSTOM,
--GEO_COUNTRY_WID,
--GEO_WID,
UPD_FLG
) as WITH CODE AS (
SELECT
W_CODE_D.MASTER_CODE AS MASTER_CODE,
W_CODE_D.MASTER_VALUE AS MASTER_VALUE,
W_CODE_D.SOURCE_CODE AS SOURCE_CODE,
W_CODE_D.DATASOURCE_NUM_ID AS DATASOURCE_NUM_ID,
W_CODE_D.SOURCE_CODE_1 as SOURCE_CODE_1,
W_CODE_D.SOURCE_CODE_2 as SOURCE_CODE_2,
W_CODE_D.SOURCE_NAME_1 as SOURCE_NAME_1,
W_CODE_D.CATEGORY
FROM
W_CODE_D
WHERE
W_CODE_D.LANGUAGE_CODE = 'E'
),
USER_TAB as (
SELECT
LOOKUP_TABLE.ROW_WID as ROW_WID,
LOOKUP_TABLE.DATASOURCE_NUM_ID as DATASOURCE_NUM_ID,
LOOKUP_TABLE.INTEGRATION_ID as INTEGRATION_ID,
LOOKUP_TABLE.EFFECTIVE_FROM_DT as EFFECTIVE_FROM_DT,
LOOKUP_TABLE.EFFECTIVE_TO_DT as EFFECTIVE_TO_DT
FROM
DW_RRX.W_USER_D LOOKUP_TABLE
),
BUSN_LOCATION as (
SELECT
sq.BUSN_LOC_NAME,
sq.BUSN_LOC_NUM,
sq.BUSN_LOC_TYPE,
sq.ST_ADDRESS1,
sq.ST_ADDRESS2,
case when CITY.MASTER_VALUE is null then (
case when sq.CITY_NAME is null
OR LENGTH(sq.CITY_NAME) = 0
OR REGEXP_INSTR(sq.CITY_NAME, ' ')> 0 then 'Unspecified' else sq.CITY_NAME end
) else CITY.MASTER_VALUE end as city_name,
sq.POSTAL_CODE,
case when STATE.MASTER_CODE is null then (
case when sq.STATE_CODE is null
OR LENGTH(sq.STATE_CODE) = 0
OR REGEXP_INSTR(sq.STATE_CODE, ' ')> 0 then 'Unspecified' else sq.STATE_CODE end
) else STATE.MASTER_CODE end as STATE_CODE,
case when COUNTRY.MASTER_CODE is null then (
case when sq.COUNTRY_CODE is null
OR LENGTH(sq.COUNTRY_CODE) = 0
OR REGEXP_INSTR(sq.COUNTRY_CODE, ' ')> 0 then 'Unspecified' else sq.COUNTRY_CODE end
) else COUNTRY.MASTER_VALUE end as COUNTRY_CODE,
'Y' as ACTIVE_FLG,
CREATED_BY.ROW_WID AS CREATED_BY_WID,
CHANGED_BY.ROW_WID AS CREATED_BY_WID,
sq.AUX1_CHANGED_ON_DT,
sq.AUX2_CHANGED_ON_DT,
sq.AUX3_CHANGED_ON_DT,
sq.AUX4_CHANGED_ON_DT,
sq.SRC_EFF_FROM_DT,
sq.SRC_EFF_TO_DT,
case when W_BUSN_LOCATION_D.INTEGRATION_ID is null then current_date else W_BUSN_LOCATION_D.W_INSERT_DT end as EFFECTIVE_FROM_DT,
TO_DATE('01013714', 'DDMMYYYY') as EFFECTIVE_TO_DT,
'N' As DELETE_FLG,
'Y' AS CURRENT_FLG,
case when W_BUSN_LOCATION_D.INTEGRATION_ID is null then current_date else W_BUSN_LOCATION_D.W_INSERT_DT end as W_INSERT_DT,
W_BUSN_LOCATION_D.W_UPDATE_DT as current_date,
sq.DATASOURCE_NUM_ID,
--sq.ETL_PROC_WID,
sq.INTEGRATION_ID,
CASE WHEN (
SELECT
ETL_PROC_WID
FROM
TEST_RRX.DW_RRX.W_PARAM_G
WHERE
ROW_WID = 1
) = W_BUSN_LOCATION_D.ETL_PROC_WID THEN 'X' WHEN W_BUSN_LOCATION_D.INTEGRATION_ID IS NULL THEN 'I' WHEN W_BUSN_LOCATION_D.INTEGRATION_ID IS NOT NULL
AND (
sq.CHANGED_ON_DT <> W_BUSN_LOCATION_D.CHANGED_ON_DT
OR sq.AUX1_CHANGED_ON_DT <> W_BUSN_LOCATION_D.AUX1_CHANGED_ON_DT
OR sq.AUX2_CHANGED_ON_DT <> W_BUSN_LOCATION_D.AUX2_CHANGED_ON_DT
OR sq.AUX3_CHANGED_ON_DT <> W_BUSN_LOCATION_D.AUX3_CHANGED_ON_DT
OR sq.AUX4_CHANGED_ON_DT <> W_BUSN_LOCATION_D.AUX4_CHANGED_ON_DT
) THEN 'U' END as UPD_FLG
FROM
DW_RRX.W_BUSN_LOCATION_DS sq
LEFT OUTER JOIN CODE COUNTRY ON COUNTRY.SOURCE_CODE = sq.country_code
AND COUNTRY.DATASOURCE_NUM_ID = sq.DATASOURCE_NUM_ID
AND COUNTRY.CATEGORY = 'COUNTRY'
LEFT OUTER JOIN CODE CITY ON CITY.SOURCE_CODE_1 = sq.country_code
AND CITY.DATASOURCE_NUM_ID = sq.DATASOURCE_NUM_ID
AND CITY.SOURCE_CODE_2 = sq.STATE_CODE
AND CITY.SOURCE_NAME_1 = sq.CITY_NAME
AND CITY.CATEGORY = 'CITY'
LEFT OUTER JOIN CODE STATE ON STATE.DATASOURCE_NUM_ID = sq.DATASOURCE_NUM_ID
AND STATE.CATEGORY = 'STATE'
LEFT OUTER JOIN USER_TAB CREATED_BY ON sq.DATASOURCE_NUM_ID = CREATED_BY.DATASOURCE_NUM_ID
AND CREATED_BY.INTEGRATION_ID = sq.CREATED_BY_ID
and CREATED_BY.EFFECTIVE_FROM_DT <= sq.CREATED_ON_DT
and CREATED_BY.EFFECTIVE_TO_DT >= sq.CREATED_ON_DT
LEFT OUTER JOIN USER_TAB CHANGED_BY ON sq.DATASOURCE_NUM_ID = CHANGED_BY.DATASOURCE_NUM_ID
AND CHANGED_BY.INTEGRATION_ID = sq.CHANGED_BY_ID
and CHANGED_BY.EFFECTIVE_FROM_DT <= sq.CHANGED_ON_DT
and CHANGED_BY.EFFECTIVE_TO_DT >= sq.CHANGED_ON_DT
LEFT OUTER JOIN W_BUSN_LOCATION_D ON sq.INTEGRATION_ID = W_BUSN_LOCATION_D.INTEGRATION_ID
AND sq.DATASOURCE_NUM_ID = W_BUSN_LOCATION_D.DATASOURCE_NUM_ID
)
SELECT
*
FROM
BUSN_LOCATION
WHERE
UPD_FLG <> 'X'
Getting SQL compilation error: Invalid column definition list
Needs to create view with above columns
I have a merge statement in which I'd like to update my table rows in case any of the columns have a different value. But it seems like even though most of the rows in the source table have remained intact, the MERGE statement performs an UPDATE on at least counts what it does an UPDATE.
DECLARE #SummaryOfChanges TABLE(Change VARCHAR(50));
MERGE MyTarget AS TARGET
USING MySource AS SOURCE
ON (SOURCE.customeridHash = TARGET.Id)
WHEN MATCHED AND (TARGET.IsCompany <> SOURCE.company
OR TARGET.Gender <> SOURCE.gender
OR TARGET.BirthDate <> CONVERT(DATE, SOURCE.dateofbirth)
OR TARGET.ZipCode <> SOURCE.ZipCode
OR TARGET.City <> SOURCE.City
OR TARGET.WantsEmail <> (CASE WHEN SOURCE.noemail = 0 THEN 1 ELSE 0 END)
OR TARGET.WantsSMS <> (CASE WHEN SOURCE.nosms = 0 THEN 1 ELSE 0 END)
OR TARGET.WantsDM <> (CASE WHEN SOURCE.nodirectmarketing = 0 THEN 1 ELSE 0 END)
OR TARGET.WantsTM <> (CASE WHEN SOURCE.notelemarketing = 0 THEN 1 ELSE 0 END)
OR TARGET.HasEmail <> SOURCE.HasEmail
OR TARGET.HasMobilePhoneNumber <> SOURCE.HasMobilePhoneNumber
OR TARGET.HasPhoneNumber = SOURCE.HasPhoneNumber
OR TARGET.Created <> SOURCE.Created
OR TARGET.Updated <> SOURCE.changed)
THEN
UPDATE SET TARGET.IsCompany = SOURCE.company,
TARGET.Gender = SOURCE.gender,
TARGET.BirthDate = CONVERT(DATE, SOURCE.dateofbirth),
TARGET.ZipCode = SOURCE.ZipCode,
TARGET.City = SOURCE.City,
TARGET.WantsEmail = (CASE WHEN SOURCE.noemail = 0 THEN 1 ELSE 0 END),
TARGET.WantsSMS = (CASE WHEN SOURCE.nosms = 0 THEN 1 ELSE 0 END),
TARGET.WantsDM = (CASE WHEN SOURCE.nodirectmarketing = 0 THEN 1 ELSE 0 END),
TARGET.WantsTM = (CASE WHEN SOURCE.notelemarketing = 0 THEN 1 ELSE 0 END),
TARGET.HasEmail = SOURCE.HasEmail,
TARGET.HasMobilePhoneNumber = SOURCE.HasMobilePhoneNumber,
TARGET.HasPhoneNumber = SOURCE.HasPhoneNumber,
TARGET.Created = SOURCE.Created,
TARGET.Updated = SOURCE.changed
WHEN NOT MATCHED BY TARGET THEN
INSERT (
Id,
IsCompany,
Gender,
BirthDate,
ZipCode,
City,
WantsEmail,
WantsSMS,
WantsDM,
WantsTM,
HasEmail,
HasMobilePhoneNumber,
HasPhoneNumber,
Created,
Updated
)
VALUES (
SOURCE.customeridHash,
SOURCE.company,
SOURCE.gender,
CONVERT(DATE, SOURCE.dateofbirth),
SOURCE.ZipCode,
SOURCE.City,
(CASE WHEN SOURCE.noemail = 0 THEN 1 ELSE 0 END),
(CASE WHEN SOURCE.nosms = 0 THEN 1 ELSE 0 END),
(CASE WHEN SOURCE.nodirectmarketing = 0 THEN 1 ELSE 0 END),
(CASE WHEN SOURCE.notelemarketing = 0 THEN 1 ELSE 0 END),
SOURCE.HasEmail,
SOURCE.HasMobilePhoneNumber,
SOURCE.HasPhoneNumber,
SOURCE.Created,
SOURCE.changed
)
WHEN NOT MATCHED BY SOURCE THEN DELETE
OUTPUT $action INTO #SummaryOfChanges;
SELECT Change, COUNT(*) CountPerChange
FROM #SummaryOfChanges
GROUP BY Change;
I do some bookkeeping at the end of the update (the final SELECT) and it seems like almost all the rows that are not new, were updated. Is this a common behavior or is there really a value amongst my <> comparison for WHEN MATCHED AND... that is updated?
Update: As suggested by one of the comments, I wrote the following test to check whether my conditions trigger an update or not:
-- TEST MERGE
select count(*)
from MyTarget TARGET join MySource SOURCE on TARGET.Id=SOURCE.customeridHash
where TARGET.IsCompany <> SOURCE.company
OR TARGET.Gender <> SOURCE.gender
OR TARGET.BirthDate <> CONVERT(DATE, SOURCE.dateofbirth)
OR TARGET.ZipCode <> SOURCE.ZipCode
OR TARGET.City <> SOURCE.City
OR TARGET.WantsEmail <> (CASE WHEN SOURCE.noemail = 0 THEN 1 ELSE 0 END)
OR TARGET.WantsSMS <> (CASE WHEN SOURCE.nosms = 0 THEN 1 ELSE 0 END)
OR TARGET.WantsDM <> (CASE WHEN SOURCE.nodirectmarketing = 0 THEN 1 ELSE 0 END)
OR TARGET.WantsTM <> (CASE WHEN SOURCE.notelemarketing = 0 THEN 1 ELSE 0 END)
OR TARGET.HasEmail <> SOURCE.HasEmail
OR TARGET.HasMobilePhoneNumber <> SOURCE.HasMobilePhoneNumber
OR TARGET.HasPhoneNumber = SOURCE.HasPhoneNumber
OR TARGET.Created <> SOURCE.Created
OR TARGET.Updated <> SOURCE.changed;
I realised that this query returns the same number of updates. So it is somehow more about the condition that the MERGE statement. But I wonder how they trigger updates.
I think I found my own mistake, in the conditions I write:
OR TARGET.HasPhoneNumber = SOURCE.HasPhoneNumber
Which almost always renders true!
I would like to use the code below to group results by OrgName but rollup the count using TotalCount
Results would look similar to the screenshot below:(sorry I had to redact information due to confidentiality agreement).
The Orgname is grouped correctly. However, I am having a little troubling rolling up totalCount.
Thanks
WITH
ctePreAgg AS
(
SELECT (ElectionName + ' - ' + CAST(ClosingDate AS VARCHAR(12))) electionName, CASE WHEN Position='Member' THEN '' ELSE Position END As Position, CASE WHEN c.CurrentOfficeHolder='Incumbent' THEN CandidateName + '('+ c.CurrentOfficeHolder + ')' ELSE CandidateName END As CandidateName , c.PositionId,COUNT(*) TotalVotes
FROM Candidates c
JOIN Positions p ON c.PositionId = p.PositionId
JOIN Elections e on c.ElectionId = e.ElectionId
WHERE c.ElectionId IN (1,2,3)
GROUP BY Position, CandidateId, CandidateName,c.PositionId,CurrentOfficeHolder,AnswerType,ElectionName, ClosingDate
)
SELECT [OrgName] = CASE WHEN GROUPING(mh.PositionId) = 0 THEN MAX(mh.Position) ELSE mh.ElectionName END
,Names = CASE WHEN GROUPING(mh.PositionId) = 0 THEN MAX(mh.CandidateName) ELSE '' END
,PositionId = CASE WHEN GROUPING(mh.PositionId) = 0 THEN mh.PositionId ELSE '' END
,TotalCount = CASE WHEN GROUPING(mh.PositionId) = 0 THEN COUNT(*) ELSE '' END
FROM ctePreAgg mh
GROUP BY ElectionName,PositionId WITH ROLLUP
HAVING GROUPING(mh.ElectionName) = 0
ORDER BY mh.ElectionName, GROUPING(mh.PositionId) DESC, mh.PositionID;
So I'm pretty new to this program and cannot figure out why I am getting this error.
Here is the qry.
SELECT policy_no,
phase_code,
sub_phase_code,
Duplicate_Indicator = CASE
WHEN Sum(1) <> 1 THEN 'DUPLICATE'
ELSE 'NOT DUPLICATE'
END
FROM qrypolicylistfornydefpremasset_re
RIGHT JOIN (SELECT TOP 100 PERCENT tblinsurance.policy_no,
tblinsurance.phase_code,
tblinsurance.sub_phase_code,
tblinsurance.prodtype,
tblinsurance.paid_to_date,
tblinsurance.val_date,
tblinsurance.issue_date,
tblinsurance.schednp,
Sum(tblinsurance.gross_annlzd_prem) AS
SumOfGROSS_ANNLZD_PREM,
Sum(tblinsurance.statnetpremium) AS
SumOfStatNetPremium,
Sum(tblinsurance.netdefpremium) AS
SumOfNetDefPremium,
Sum(tblinsurance.netdefextra) AS
SumOfNetDefExtra,
Sum(tblinsurance.netdefpremiumadj) AS
SumOfNetDefPremiumAdj,
Sum(tblinsurance.netdefextraadj) AS
SumOfNetDefExtraAdj,
NetvsGrossInd = CASE
WHEN
[netdefpremium] = [netdefpremiumadj]
THEN
'Net'
ELSE 'Gross'
END,
Sum(tblinsurance.amount_inforce) AS
SumOfAMOUNT_INFORCE,
Sum(tblinsurance.pua_face) AS
SumOfPUA_FACE,
Sum(tblinsurance.oyt_face) AS
SumOfOYT_FACE
FROM tblinsurance
WHERE ( ( ( tblinsurance.company_code ) = 'NL' )
AND ( ( tblinsurance.term_reason ) = 'A' )
AND ( ( tblinsurance. issue_date ) <= [val_date] ) )
GROUP BY tblinsurance.policy_no,
tblinsurance.phase_code,
tblinsurance.sub_phase_code,
tblinsurance.prodtype,
tblinsurance.paid_to_date,
tblinsurance.val_date,
tblinsurance.issue_date,
tblinsurance.schednp,
CASE
WHEN [netdefpremium] = [netdefpremiumadj] THEN
'Net'
ELSE 'Gross'
END
HAVING (( ( Sum(tblinsurance.netdefpremium) ) <> 0 )))Work
ON policy_no = qrypolicylistfornydefpremasset_re.policy_no
AND phase_code = qrypolicylistfornydefpremasset_re.phase_code
AND sub_phase_code =
qrypolicylistfornydefpremasset_re.sub_phase_code
GROUP BY policy_no,
phase_code,
sub_phase_code
Where I am getting the ambiguous colum name is on the Fields POLICY_NO, PHASE_CODE, SUB_PHASE_CODE, but only in the On and GROUP by at the end and the ones in the SELECT in the beginning.
well, you've got these fields in both
qryPolicyListforNYDefPRemAsset_Re
and in your subquery Work
so prefix them with the right table (or better, use aliases).
I prefixed with Work in SELECT and GROUP BY and JOIN I may be wrong for SELECT and GROUP BY (maybe you need q, alias for qryPolicyListforNYDefPRemAsset_Re) :I'm like Sql, your query is too ambiguous for me ;)
SELECT
Work.POLICY_NO,
Work.PHASE_CODE,
Work.SUB_PHASE_CODE,
Duplicate_Indicator = case when
SUM(1) <> 1 then 'DUPLICATE'
else 'NOT DUPLICATE'
end
FROM
qryPolicyListforNYDefPRemAsset_Re q
RIGHT JOIN
(SELECT top 100 percent
t.POLICY_NO,
t.PHASE_CODE,
t.SUB_PHASE_CODE,
t.ProdType,
t.PAID_TO_DATE,
t.VAL_DATE,
t.ISSUE_DATE,
t.SchedNP,
Sum(t.GROSS_ANNLZD_PREM) AS SumOfGROSS_ANNLZD_PREM,
Sum(t.StatNetPremium) AS SumOfStatNetPremium,
Sum(t.NetDefPremium) AS SumOfNetDefPremium,
Sum(t.NetDefExtra) AS SumOfNetDefExtra,
Sum(t.NetDefPremiumAdj) AS SumOfNetDefPremiumAdj,
Sum(t.NetDefExtraAdj) AS SumOfNetDefExtraAdj,
NetvsGrossInd = Case when [NetDefPremium]=[NetDefPremiumAdj] then 'Net' Else 'Gross' END,
Sum(t.AMOUNT_INFORCE) AS SumOfAMOUNT_INFORCE,
Sum(t.PUA_FACE) AS SumOfPUA_FACE,
Sum(t.OYT_FACE) AS SumOfOYT_FACE
FROM tblInsurance t
WHERE (((t.COMPANY_CODE)='NL') AND ((t.TERM_REASON)='A') AND ((t.ISSUE_DATE)<=[VAL_DATE]))
GROUP BY
t.POLICY_NO,
t.PHASE_CODE,
t.SUB_PHASE_CODE,
t.ProdType,
t.PAID_TO_DATE,
t.VAL_DATE,
t.ISSUE_DATE,
t.SchedNP,
Case when [NetDefPremium]=[NetDefPremiumAdj] then 'Net' Else 'Gross' END
HAVING (((Sum(t.NetDefPremium))<>0))
)Work
ON
Work.POLICY_NO = q.POLICY_NO AND
Work.qPHASE_CODE= q.PHASE_CODE AND
Work.SUB_PHASE_CODE = q.SUB_PHASE_CODE
GROUP BY
Work.POLICY_NO,
Work.PHASE_CODE,
Work.SUB_PHASE_CODE
I have something like
(COMPLEX_EXPRESSION_N stands for a long subquery)
select
ID_Operation,
FirstCheck = CASE WHEN (COMPLEX_EXPRESSION_1)= 0 then 0 else 1 end,
SecondCheck = CASE WHEN (COMPLEX_EXPRESSION_2)= 0 then 0 else 1 end,
ThirdCheck = CASE WHEN (COMPLEX_EXPRESSION_3)= 0 then 0 else 1 end,
AllChecksOk = Case WHEN
(FirstCheck + SecondCheck + Third CHeck = 3)
Then 'OK' Else 'No' End
from
AllOperationsTable
Is it possible to use FirstCheck, SecondCheck, ThirdCheck as I did in the AllChecksOk line?
I am not concerned about performance, this is something that is manually run once a day on a very small number of records, I just want to avoid to create views, tables or temporary tables and keep all in a single select statement.
As an altenrative I can do this, but it makes the query less readable (as I need to write twice every complex expression):
select
ID_Operation,
FirstCheck = CASE WHEN (COMPLEX_EXPRESSION_1)= 0 then 0 else 1 end,
SecondCheck = CASE WHEN (COMPLEX_EXPRESSION_2)= 0 then 0 else 1 end,
ThirdCheck = CASE WHEN (COMPLEX_EXPRESSION_3)= 0 then 0 else 1 end,
AllChecksOk = Case WHEN
(COMPLEX_EXPRESSION_1+ COMPLEX_EXPRESSION_2+
COMPLEX_EXPRESSION_3CHeck = 3) Then 'OK' Else 'No' End
from
AllOperationsTable
You can't reference a column alias in the select but you can use a CTE as below.
;WITH CTE AS
(
select
ID_Operation,
FirstCheck = CASE WHEN (COMPLEX_EXPRESSION_1)= 0 then 0 else 1 end,
SecondCheck = CASE WHEN (COMPLEX_EXPRESSION_2)= 0 then 0 else 1 end,
ThirdCheck = CASE WHEN (COMPLEX_EXPRESSION_3)= 0 then 0 else 1 end
from
AllOperationsTable
)
SELECT *,
AllChecksOk = Case WHEN
(COMPLEX_EXPRESSION_1+ COMPLEX_EXPRESSION_2+
COMPLEX_EXPRESSION_3CHeck = 3) Then 'OK' Else 'No' End
FROM CTE
You can also use CROSS APPLY to define the 3 column aliases then reference them in the main SELECT list as in this example.
Below is a derived table solution
SELECT
T.ID_Operation,
FirstCheck = CASE WHEN T.Expr1 = 0 THEN 0 ELSE 1 END,
SecondCheck = CASE WHEN T.Expr2 = 0 THEN 0 ELSE 1 END,
ThirdCheck = CASE WHEN T.Expr3 = 0 THEN 0 ELSE 1 END,
AllChecksOk = CASE WHEN T.Expr1 + T.Expr2 + T.Expr3 = 3 THEN 'OK' ELSE 'No' END
FROM
(
SELECT
ID_Operation,
Expr1 = (COMPLEX_EXPRESSION_1),
Expr2 = (COMPLEX_EXPRESSION_2),
Expr3 = (COMPLEX_EXPRESSION_3)
FROM
AllOperationsTable
) T
Personally, I find using CTE or derived tables a bit confusing for this purpose, as you have to nest things one level and think about the nesting impliciations. A much simpler approach (at least in my opinion) is to use APPLY (or standard SQL LATERAL in other RDBMS) to generate column expression aliases:
SELECT
ID_Operation,
FirstCheck,
SecondCheck,
ThirdCheck,
AllChecksOk = CASE
WHEN FirstCheck + SecondCheck + ThirdCheck = 3 THEN 'OK' ELSE 'NO'
END
FROM
AllOperationsTable
CROSS APPLY (
SELECT
FirstCheck = CASE WHEN COMPLEX_EXPRESSION_1 = 0 THEN 0 ELSE 1 END,
SecondCheck = CASE WHEN COMPLEX_EXPRESSION_1 = 0 THEN 0 ELSE 1 END,
ThirdCheck = CASE WHEN COMPLEX_EXPRESSION_1 = 0 THEN 0 ELSE 1 END
) t