SELECT DT.TenantDescription
,DT.PropertyNumber
,DT.UnitNo
,DT.AdressLn1
,DT.AddressLn2
,DT.AddressSituation
,(
CASE
WHEN DT.TransactionCode = 1
THEN DT.New_TransactionValue
ELSE 0
END
) AS RentDue
,(
CASE
WHEN DT.TransactionCode = 2
THEN DT.New_TransactionValue
ELSE 0
END
) AS OTHERSUMSDUE
,(
CASE
WHEN DT.TransactionCode = 3
THEN DT.New_TransactionValue
ELSE 0
END
) AS ARREARSBFWD
,(
CASE
WHEN DT.TransactionCode = 4
THEN DT.New_TransactionValue
ELSE 0
END
) AS ARREARSCFWD
,(
CASE
WHEN DT.TransactionCode = 5
THEN DT.New_TransactionValue
ELSE 0
END
) AS IRRECOVERABLERENT
,(
CASE
WHEN DT.TransactionCode > 5
THEN DT.New_TransactionValue
ELSE 0
END
) AS Expenditure
FROM (
SELECT * * (
SELECT New_TenantNameOnly
FROM New_Rentmaster Rm
WHERE Rm.New_rentmasterId = PD.new_rentmasterid
) AS TenantDescription
,* * (
SELECT [New_UnitNumber]
FROM new_propertyunits NPU
WHERE NPU.[New_propertyunitsId] = PD.[new_unitnumberid]
) AS UnitNo
,(
SELECT New_AddressLine1
FROM New_address
WHERE New_addressId = (
SELECT New_addressid
FROM New_PropertyMaster PM
WHERE PM.new_propertymasterid = PD.[new_propertynumbernameid]
)
) AS AdressLn1
,(
SELECT New_AddressLine2
FROM New_address
WHERE New_addressId = (
SELECT New_addressid
FROM New_PropertyMaster PM
WHERE PM.new_propertymasterid = PD.[new_propertynumbernameid]
)
) AS AddressLn2
,(
SELECT TT.[New_TransactionTypeCode] AS TransactionCode
FROM New_transactiontype TT
WHERE [New_transactiontypeId] = PD.[new_transactioncodenameid]
) AS TransactionCode
,(
SELECT New_PropertyNumber
FROM New_PropertyMaster PM
WHERE PM.new_propertymasterid = PD.[new_propertynumbernameid]
) AS PropertyNumber
,(
SELECT New_UnitAddressIdName
FROM New_propertyunits NPU
WHERE NPU.[New_propertyunitsId] = PD.[new_unitnumberid]
) AS AddressSituation
,PD.New_TransactionValue
FROM New_PropertyDetails PD
) AS DT
The above piece of code works fine
Now I want to make changes to the above column (the name is aliased to TenantDescription)
where I want to replace the above column with the following code
Select New_TenantNameOnly from New_Rentmaster Rm
New_TenantNumber IN
(Select MAX(New_TenantNumber) from new_rentmaster GROUP BY [New_Unit_No],[New_Propety_Number])
then it gives me an error
Subquery returns more than one value
This code is supposed to return more than one value
So what should I do about it >??
If you're wanting to bring back multiple results, you ought to be thinking about using joins rather than subqueries. An Inner Join looks something like this:
SELECT *
FROM HumanResources.Employee AS e
INNER JOIN Person.Person AS p
ON e.BusinessEntityID = p.BusinessEntityID
this will produce as many rows as can be produced by matching rows from each table based on the ON condition (e.g. if there are two rows in Employee with BusinessEntityID of 1, and three rows in Person with BusinessEntityID of 1, the above will produce six rows in the result set where BusinessEntityID is 1)
Related
I am new in MySQL I have a db2 select and a would like to do this in MSsql and with WITH clause
db2
1 SQL.
SELECT
SQLUSER.TT_VALUTRAZ.SIFRA3,
SQLUSER.TT_VALUTRAZ.SIFVAL32,
SQLUSER.TT_VALUTRAZ.DATUM,
SQLUSER.TT_VALUTRAZ.RAZMERJE
FROM
SQLUSER.TT_VALUTRAZ
WHERE
(
(SQLUSER.TT_VALUTRAZ.DATUM >= '1.5.2007')
) ---> this go to DW.TEMP_PFPC_TT_VALUTRAZ
2 sql.
SELECT
'705' AS SIFRA3,
'891' AS SIFVAL32,
A.DATUM,
A.RAZMERJE AS RAZMERJE
FROM
DW.TEMP_PFPC_TT_VALUTRAZ A
WHERE
A.DATUM >= '1.5.2007' AND
A.SIFRA3 = '891' AND
A.SIFVAL32 = '978' AND
('705', '891', A.DATUM) NOT IN
(
SELECT
SIFRA3,
SIFVAL32,
DATUM
FROM
DW.TEMP_PFPC_TT_VALUTRAZ
WHERE
SIFRA3 = '705' AND
SIFVAL32 = '891'
)
now I like to join this two SQL statement and would like to use ons with clause and MSsql syntax
There are many ways of doing this. I only posted one way. There are some places that have been changed due to syntax issues. Let me know this answer if this answer is useful.
; WITH CTE_1 AS ( SELECT
SQLUSER.TT_VALUTRAZ.SIFRA3,
SQLUSER.TT_VALUTRAZ.SIFVAL32,
SQLUSER.TT_VALUTRAZ.DATUM,
SQLUSER.TT_VALUTRAZ.RAZMERJE
FROM
SQLUSER.TT_VALUTRAZ
WHERE
(
(SQLUSER.TT_VALUTRAZ.DATUM >= '1.5.2007')
) ---> this go to DW.TEMP_PFPC_TT_VALUTRAZ
)
, CTE_2 AS (
SELECT * FROM
(
SELECT
'705' AS SIFRA3,
'891' AS SIFVAL32,
A.DATUM,
A.RAZMERJE AS RAZMERJE
FROM
DW.TEMP_PFPC_TT_VALUTRAZ A
) AS B
WHERE
B.DATUM >= '1.5.2007' AND
B.SIFRA3 = 891 AND
B.SIFVAL32 = 978 AND
B.SIFRA3 NOT IN (705) --use of sub queries in where clause has been fixed.
AND B.SIFVAL32 NOT IN (891) --use of sub queries in where clause has been fixed.
AND B.DATUM NOT IN
(
SELECT
DATUM
FROM
DW.TEMP_PFPC_TT_VALUTRAZ
)
)
SELECT * FROM
CTE_1 AS [C]
INNER JOIN CTE_2 AS [CT]
ON [CTE_1]. [SIFRA3] = [CT].[SIFRA3]
AND [C]. [SIFVAL32] = [CT].[SIFVAL32]
AND [C].[DATUM] = [CT].[DATUM]
AND [C].[RAZMERJE] = [CT].[RAZMERJE]
I'm obviously new to this and I need some help. I have this code in SQL Server Management Studio.
The error that I get is
Msg 156, Level 15, State 1, Line 38
Incorrect syntax near the keyword 'IF'
If I execute direct select statement instead of using "If" the query is successfully executed.
Please point out what I am missing and where is my mistake.
Thanks a lot.
declare #dateFrom [date] = cast(dateadd(day, -7, getdate()) as [date]);
declare #dateTo [date] = cast(dateadd(day, 28, getdate()) as [date]);
declare #prTypeCode [varchar](10) = null;
declare #ExcludeA [bit] = 0 ;
declare #ExcludeB [bit] = 0;
;with distribution as
(
select *
from [schema1].[Table1]
),
product as
(
select *
from [schema1].[Product]
),
fint as
(
select
*,
(case when CHARINDEX('0%', FIN_ CODE) > 0 then 1 else 0 end) as ZFlag
from [schema1].[FinTab]
),
deal as
(
select
*,
case when (AG_ID = 5 or DE_ID = 6) then 1
else 0 end as Ex_flag
from
[P_ BASE1].[ schema2].[table3]
),
dealersn as
(
select distinct *
from [P_ BASE1].[ schema2].[table4]
),
regionN as
(
select distinct *
from [P_ BASE1].[ schema2].[table5]
),
final as
(
select
d.PRODUCT_CODE, p.PR_NAME, p.PR_TYPE_CODE, p.PR_ACTIVE,
d.FIN_TABLE_CODE, ft.FT_NAME, ft.FT_ACTIVE,
cast(d.SND_TO_DATE as [date]) as SND_TO_DATE,
count(d.SN_ID) as SHOP_COUNT,
min(ft.ZFlag) as ZFlag,
min(ds.Ex_flag) as ExFlag, dn.SND_FULLNAME,rn.REG_NAME
from
distribution d
left outer join
product p on p.PRODUCT_CODE = d.PRODUCT_CODE
left outer join
fint ft on ft. FIN_ CODE = FIN_ CODE
left outer join
deal as ds On d.SN_ID = ds.SHOP_ID
left outer join
dealersn as dn on d.SN_ID = dn.SN_DATA_ID
left outer join
regionN as rn ON ds.REGION_ID = rn.REGION_ID
where
d.SND_TO_DATE between #dateFrom and #dateTo
and (#prTypeCode is null or p.PR_TYPE_CODE = #prTypeCode)
group by
rn.REG_NAME, ds.REGION_ID, ds.SHOP_ID, d.PRODUCT_CODE, p.PR_NAME,
p.PR_TYPE_CODE, p.PR_ACTIVE, d.FIN_TABLE_CODE, ft.FT_NAME,
ft.FT_ACTIVE, d.SND_TO_DATE,dn.SND_FULLNAME
)
IF (#ZeroPercent = 0 AND #LargeChainsOrTushev = 0)
BEGIN
SELECT DISTINCT *
FROM final
WHERE ZFlag = 0 AND ExFlag = 0
END
ELSE
IF #ZeroPercent = 1 AND #LargeChainsOrTushev = 0
BEGIN
SELECT DISTINCT *
FROM final
WHERE ZFlag = 1 AND ExFlag = 0
END
ELSE IF #ZeroPercent = 0 AND #LargeChainsOrTushev = 1
BEGIN
SELECT DISTINCT *
FROM final
WHERE ZFlag = 0 AND ExFlag = 1
END
ELSE
BEGIN
SELECT DISTINCT *
FROM final
END
You have a with statement that "defines" a bunch of tables, the last of which is called final. This is called a CTE (Common Table Expression). You can use CTEs for many reasons, but the important thing is, you have to use the CTE in a query. Instead you define the CTE and then...do nothing.
If you put a line like this:
select * from final
just after the CTE (before the IF), it will run.
Currently I have a udf which returns a table. it returns 3 rows . Each row return the parameter's value *10
Something like (pseudo):
ALTER FUNCTION [dbo].[myUdf]
(
#num int
)
RETURNS #myTable TABLE (h int )
AS
begin
insert into #myTable
SELECT h=#num * 10 UNION
SELECT h=#num * 20 UNION
SELECT h=#num * 30
return #myTable
end
Ok.
Now , in my code I do something like :
select .... ,
has20 = CASE WHEN EXISTS (SELECT 1 FROM dbo.myUdf(A.ID) WHERE h=20)
THEN 0 ELSE 1 end
,
has30 = CASE WHEN EXISTS (SELECT 1 FROM dbo.myUdf(A.ID) WHERE h=30)
THEN 0 ELSE 1 end
...
from A join B...on ...
Where x .. or ..y ... or Exists (select 1 from dbo.myUdf(A.ID) )
Please notice multiple usages :
Ok. So I was told to use Cross apply and so I did :
So let's take a real simple example :
I have this 3 rows of data :
DECLARE #t TABLE(myNum INT)
INSERT #t
VALUES (1), (2), (3)
so let's use cross apply :
SELECT has20 = CASE WHEN EXISTS( SELECT h FROM myCrossApply WHERE mynum=20 )
THEN '1' ELSE '0' END ,
has30 = CASE WHEN EXISTS( SELECT h FROM myCrossApply WHERE mynum=30 )
THEN '1' ELSE '0' END
FROM #t tmp
CROSS APPLY (
-- notice ! in reality there is a udf Table here , I jsut made a simple conversion insted so you can test it.
SELECT h = tmp.myNum * 10 UNION SELECT h = tmp.myNum * 20 UNION SELECT h = tmp.myNum * 30
) myCrossApply
But there is 2 errors here Which I don't know how to solve :
Question #1
It doesn't recognize myCrossApply in the EXISTS clause :
How can I solve this ?
Question #2
Also , the rows are mutipled becuase of the cross apply
For example ( let's remove the unknown exists clause to show the second problem) :
SELECT dummy = tmp.myNum , myCrossApply.h
/*...*/
FROM #t tmp
CROSS APPLY (
SELECT h = tmp.myNum * 10 UNION SELECT h = tmp.myNum * 20 UNION SELECT h = tmp.myNum * 30
) myCrossApply
How can I solve this ?
I just don't want the UDF to be recalculated each time , so they suggested to use cross apply.
myCrossApply is not a real table, it is a reference to a alias for a subset of data.
You would not be able to refer to tmp as a table either.
Here is some code that should use the same logic as your script:
declare #t table(mynum int)
insert #t values(1),(2),(3)
SELECT has20 = myCrossApply.chk1,
has30 = myCrossApply.chk2,
mynum
FROM #t tmp
CROSS APPLY (
SELECT
max(case when h = 20 then 1 else 0 end) chk1,
max(case when h = 30 then 1 else 0 end) chk2
FROM
( SELECT h = tmp.myNum * 10
UNION all
SELECT h = tmp.myNum * 20
UNION all
SELECT h = tmp.myNum * 30) x
) myCrossApply
Result:
has20 has30 mynum
1 1 1
1 0 2
0 1 3
Here's my Count_query:
Declare #yes_count decimal;
Declare #no_count decimal;
set #yes_count=(Select count(*) from Master_Data where Received_Data='Yes');
set #no_count=(Select count(*) from Master_Data where Received_Data='No');
select #yes_count As Yes_Count,#no_count as No_Count,(#yes_count/(#yes_count+#no_count)) As Submission_Count
I am having trouble making joins on these two queries
This is the rest of the query:
Select Distinct D.Member_Id,d.Name,d.Region_Name, D.Domain,e.Goal_Abbreviation,
e.Received_Data, case when Received_Data = 'Service Not Provided' then null
when Received_Data = 'No' then null else e.Improvement end as
Percent_Improvement , case when Received_Data = 'Service Not Provided' then null
when Received_Data = 'No' then null else e.Met_40_20 end as Met_40_20
FROM (
select distinct member_Domains.*,
(case when NoData.Member_Id is null then 'Participating' else ' ' end) as Participating
from
(
select distinct members.Member_Id, members.Name, Members.Region_Name,
case when Domains.Goal_Abbreviation = 'EED Reduction' then 'EED'
When Domains.Goal_Abbreviation = 'Pressure Ulcers' then 'PRU'
when Domains.Goal_Abbreviation = 'Readmissions' then 'READ' else Domains.Goal_Abbreviation end as Domain from
(select g.* from Program_Structure as ps inner join Goal as g on ps.Goal_Id = g.Goal_Id
and ps.Parent_Goal_ID = 0) as Domains
cross join
(select distinct hc.Member_ID, hc.Name,hc.Region_Name from zsheet as z
inner join Hospital_Customers$ as hc on z.CCN = hc.Mcare_Id) as Members
) as member_Domains
left outer join Z_Values_Hospitals as NoData on member_Domains.member_ID = NoData.Member_Id
and Member_Domains.Domain = noData.ReportName) D
Left Outer JOIN
(SELECT B.Member_ID, B.Goal_Abbreviation, B.minRate, C.maxRate, B.BLine, C.Curr_Quarter, B.S_Domain,
(CASE WHEN B.Member_ID IN
(SELECT member_id
FROM Null_Report
WHERE ReportName = B.S_Domain) THEN 'Service Not Provided' WHEN Curr_Quarter = 240 THEN 'Yes' ELSE 'No' END) AS Received_Data,
ROUND((CASE WHEN minRate = 0 AND maxRate = 0 THEN 0 WHEN minRate = 0 AND maxRate > 0 THEN 1 ELSE (((maxRate - minRate) / minRate) * 100) END), .2) AS Improvement,
(CASE WHEN ((CASE WHEN minRate = 0 AND maxRate = 0 THEN 0 WHEN minRate = 0 AND maxRate > 0 THEN 1 ELSE (maxRate - minRate) / minRate END)) <= - 0.4 OR
maxRate = 0 THEN 'Yes' WHEN ((CASE WHEN minRate = 0 AND maxRate = 0 THEN 0 WHEN minRate = 0 AND maxRate > 0 THEN 1 ELSE (maxRate - minRate) / minRate END))
<= - 0.2 OR maxRate = 0 THEN 'Yes' ELSE 'No' END) AS Met_40_20
FROM (SELECT tab.Member_ID, tab.Measure_Value AS minRate, tab.Goal_Abbreviation, A.BLine, tab.S_Domain
FROM Measure_Table_Description AS tab INNER JOIN
(SELECT DISTINCT
Member_ID AS new_memid, Goal_Abbreviation AS new_measure, MIN(Reporting_Period_ID) AS BLine, MAX(Reporting_Period_ID)
AS Curr_Quarter
FROM Measure_Table_Description
WHERE (Member_ID > 1) AND (Measure_Value IS NOT NULL) AND (Measure_ID LIKE '%O%')
GROUP BY Goal_Abbreviation, Member_ID) AS A ON tab.Member_ID = A.new_memid AND tab.Reporting_Period_ID = A.BLine AND
tab.Goal_Abbreviation = A.new_measure) AS B FULL OUTER JOIN
(SELECT tab.Member_ID, tab.Measure_Value AS maxRate, tab.Goal_Abbreviation, A_1.Curr_Quarter
FROM Measure_Table_Description AS tab INNER JOIN
(SELECT DISTINCT
Member_ID AS new_memid, Goal_Abbreviation AS new_measure,
MIN(Reporting_Period_ID) AS BLine, MAX(Reporting_Period_ID)
AS Curr_Quarter
FROM Measure_Table_Description AS Measure_Table_Description_1
WHERE (Member_ID >1) AND (Measure_Value IS NOT NULL) AND (Measure_ID LIKE '%O%')
GROUP BY Goal_Abbreviation, Member_ID) AS A_1 ON tab.Member_ID = A_1.new_memid
AND tab.Reporting_Period_ID = A_1.Curr_Quarter AND
tab.Goal_Abbreviation = A_1.new_measure) AS C ON B.Member_ID = C.Member_ID
WHERE (B.Goal_Abbreviation = C.Goal_Abbreviation) ) E ON D.Member_Id = E.Member_ID AND d.Domain = E.S_Domain
ORDER BY D.Domain,D.Member_ID
How do I get a count of the 'yes'/ (count(yes)+count(no)) for each member_ID as column1 and also display the rank of each member_ID against all the member_IDs in the result as column2. I have come up with a query that generates the count for the entire table, but how do I restrict it each Member_ID.
Thanks for your help.
I haven't taken the time to digest your provided query, but if abstracted to the concept of having an aggregate over a range of data repeated on each row, you should look at using windowing functions. There are other methods, such as using a CTE to do your aggregation and then JOINing back to your detailed data. That might work better for more complex calculations, but the window functions are arguably the more elegant option.
DECLARE #MasterData AS TABLE
(
MemberID varchar(50),
MemberAnswer int
);
INSERT INTO #MasterData (MemberID, MemberAnswer) VALUES ('Jim', 1);
INSERT INTO #MasterData (MemberID, MemberAnswer) VALUES ('Jim', 0);
INSERT INTO #MasterData (MemberID, MemberAnswer) VALUES ('Jim', 1);
INSERT INTO #MasterData (MemberID, MemberAnswer) VALUES ('Jim', 1);
INSERT INTO #MasterData (MemberID, MemberAnswer) VALUES ('Jane', 1);
INSERT INTO #MasterData (MemberID, MemberAnswer) VALUES ('Jane', 0);
INSERT INTO #MasterData (MemberID, MemberAnswer) VALUES ('Jane', 1);
-- Method 1, using windowing functions (preferred for performance and syntactical compactness)
SELECT
MemberID,
MemberAnswer,
CONVERT(numeric(19,4),SUM(MemberAnswer) OVER (PARTITION BY MemberID)) / CONVERT(numeric(19,4),COUNT(MemberAnswer) OVER (PARTITION BY MemberID)) AS PercentYes
FROM #MasterData;
-- Method 2, using a CTE
WITH MemberSummary AS
(
SELECT
MemberID,
SUM(MemberAnswer) AS MemberYes,
COUNT(MemberAnswer) AS MemberTotal
FROM #MasterData
GROUP BY MemberID
)
SELECT
md.MemberID,
md.MemberAnswer,
CONVERT(numeric(19,4),MemberYes) / CONVERT(numeric(19,4),MemberTotal) AS PercentYes
FROM #MasterData md
JOIN MemberSummary ms
ON md.MemberID = ms.MemberID;
First thought is: your query is much, much too complicated. I have spent about 10 minutes now trying to make sense of it and haven't gotten anywhere, so it's obviously going to pose a long-term maintenance challenge to those within your organization going forward as well. I would really recommend you try to find some way of simplifying it.
That said, here is a simplified, general example of how to query on a calculated value and rank the results:
CREATE TABLE member (member_id INT PRIMARY KEY);
CREATE TABLE master_data (
transaction_id INT PRIMARY KEY,
member_id INT FOREIGN KEY REFERENCES member(member_id),
received_data BIT
);
-- INSERT data here
; WITH member_data_counts AS (
SELECT
m.member_id,
(SELECT COUNT(*) FROM master_data d WHERE d.member_id = m.member_id AND d.received_data = 1) num_yes,
(SELECT COUNT(*) FROM master_data d WHERE d.member_id = m.member_id AND d.received_data = 0) num_no
FROM member m
), member_data_calc AS (
SELECT
*,
CASE
WHEN (num_yes + num_no) = 0 THEN NULL -- avoid division-by-zero error
ELSE num_yes / (num_yes + num_no)
END pct_yes
FROM member_data_counts
), member_data_rank AS (
SELECT *, RANK() OVER (ORDER BY pct_yes DESC) AS RankValue
FROM member_data_calc
)
SELECT *
FROM member_data_rank
ORDER BY RankValue ASC;
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