Related
Question regarding "IN" versus "INNER JOIN" and VARCHAR versus NVARCHAR
Examples lay it out...
This query returns the CORRECT results (11 count):
Uses nvarchar(10) data columns for comparison (Id and Location) via INNER JOIN
SELECT b.Location
FROM [configuration].[dbo].[M3_Customer] a
inner join [configuration].[dbo].[M3_WarehouseInventory] b
on a.Id = b.Location
WHERE 1=1
and b.[WarehouseId] = 'NCL'
AND a.[Status] <> '90'
GROUP BY b.[Location], a.Id
This query returns the CORRECT records (11 count):
Uses the same query above as a sub-query, still comparing the same columns but using IN, and adds a forced CONVERT from NVARCHAR to VARCHAR.
SELECT *
FROM [configuration].[dbo].[M3_Customer]
WHERE 1=1
AND convert(varchar(10),[configuration].[dbo].[M3_Customer].[Id]) in (
SELECT convert(varchar(10),b.Location)
FROM [configuration].[dbo].[M3_Customer] a
inner join [configuration].[dbo].[M3_WarehouseInventory] b
on a.Id = b.Location
WHERE 1=1
and b.[WarehouseId] = 'NCL'
AND a.[Status] <> '90'
GROUP BY b.[Location], a.Id
)
This query returns INCORRECT results (10 count):
Only difference between this query and above is the comparison columns are converted to NVARCHAR
SELECT *
FROM [configuration].[dbo].[M3_Customer]
WHERE 1=1
AND convert(nvarchar(10),[configuration].[dbo].[M3_Customer].[Id]) in (
SELECT convert(nvarchar(10),b.Location)
FROM [configuration].[dbo].[M3_Customer] a
inner join [configuration].[dbo].[M3_WarehouseInventory] b
on a.Id = b.Location
WHERE 1=1
and b.[WarehouseId] = 'NCL'
AND a.[Status] <> '90'
GROUP BY b.[Location], a.Id
)
This is the original query that returned INCORRECT results - 10 records, should be returning 11 records:
The issue is associated to the difference between an INNER JOIN and IN - as well as - varchar vs nvarchar
SELECT *
FROM [configuration].[dbo].[M3_Customer]
WHERE 1=1
AND [configuration].[dbo].[M3_Customer].[Id] IN (
SELECT [configuration].[dbo].[M3_WarehouseInventory].[Location]
FROM [configuration].[dbo].[M3_WarehouseInventory]
WHERE 1=1
and [configuration].[dbo].[M3_WarehouseInventory].[WarehouseId] = 'NCL'
GROUP BY [configuration].[dbo].[M3_WarehouseInventory].[Location]
)
AND [configuration].[dbo].[M3_Customer].[Status] <> '90'
The INNER JOIN logic works with nvarchar.
The IN logic works when converting to varchar.
The IN logic using nvarchar failed to return a single record.
We applied LTRIM(RTRIM() to all columns at one point but that did not resolve the issue.
Only using the combination of IN and converting the comparison columns to varchar - resolved the issue.
Why?
I write function in PostgreSQL. I am trying to fetch data from db by passing parameters in function .But i am getting error" ERROR: structure of query does not match function result type".
Here i created a function in which i am using union to get unique values.In first select stat. i amsetting value for account total that is used in below code.
Function:
CREATE OR REPLACE FUNCTION GetDeptListForViewModifyJointUsePercentages ( p_nInstID numeric,p_nDeptID numeric)
RETURNS Table(
res_ndept_id numeric,
res_salaryPercent character varying,
res_nclient_cpc_mapping_id numeric,
res_CPCCODE character varying,
res_sdept_name character varying,
res_sclient_dept_id character varying,
res_sAlternateJointUsePercentage character varying
)
AS $$
declare v_AccountTotal numeric(18,2);
BEGIN
RETURN QUERY
select SUM(CAST (coalesce(eam.npayroll_amt, null) AS numeric(18,2))) as AccountTotal
FROM Account acct
INNER JOIN employeeaccountmapping eam
ON eam.nacct_id = acct.naccount_id
AND acct.ninst_id =p_nInstID
where acct.ndept_id =p_nDeptID ;
SELECT *
FROM
(select dep.ndept_id ,( CASE
WHEN v_AccountTotal =0 THEN 0
ELSE Round(SUM(CAST(coalesce(eam.npayroll_amt, null) AS numeric(18,2)) * cac.npercentage_assigned/100) / v_AccountTotal *100,null)
END
) as salaryPercent
,cac.nclient_cpc_mapping_id,client.sclient_cpc AS CPCCODE,
dep.sdept_name,dep.sclient_dept_id,'NO' ASsAlternateJointUsePercentage
FROM account
INNER JOIN employeeaccountmapping eam
ON eam.nacct_id = account .naccount_id AND account .ninst_id=p_nInstID
INNER JOIN accountcpcmapping acm
ON acm.naccount_cpc_mapping_id = account.naccount_cpc_mapping_id
INNER JOIN cpcaccountcpcmapping as cac
ON cac.naccount_cpc_mapping_id=acm.naccount_cpc_mapping_id
INNER JOIN clientcostpoolcodes as client
ON client.nclient_cpc_mapping_id=cac.nclient_cpc_mapping_id
INNER JOIN mastercostpoolcodes
ON mastercostpoolcodes .nmaster_cpc_id= client.nmaster_cpc_id
INNER JOIN department as dep
ON account.ndept_id=dep.ndept_id and dep.balternate_jointuse_percentage=FALSE
where account.ndept_id =p_nDeptID
Group by dep.ndept_id,cac.nclient_cpc_mapping_id,client.sclient_cpc
,dep.sdept_name,dep.sclient_dept_id, dep.balternate_jointuse_percentage
UNION
SELECT Department_1.ndept_id, a_1.SumByCPC, clientcostpoolcodes.nclient_cpc_mapping_id, clientcostpoolcodes .sclient_cpc, Department_1.sdept_name, Department_1.sclient_dept_id , 'YES' AS sAlternateJointUsePercentage
FROM department AS Department_1 LEFT OUTER JOIN
mastercostpoolcodes RIGHT OUTER JOIN
clientcostpoolcodes RIGHT OUTER JOIN
(SELECT JointUseStatistics_1.nccp_code, SUM(JointUseStatistics_1.npercent) /
(SELECT SUM(jointusestatistics.npercent) AS SumByCPC
FROM jointusestatistics INNER JOIN
roomdepartmentmapping ON jointusestatistics.nroom_allocation_id = roomdepartmentmapping .nroom_allocation_id
WHERE (roomdepartmentmapping .ndept_id = Room_1.ndept_id)) * 100 AS SumByCPC,
Room_1.ndept_id
FROM jointusestatistics JointUseStatistics_1 INNER JOIN roomdepartmentmapping AS Room_1 ON JointUseStatistics_1.nroom_allocation_id = Room_1.nroom_allocation_id
GROUP BY JointUseStatistics_1.nccp_code, JointUseStatistics_1.npercent, Room_1.ndept_id) AS a_1 ON
clientcostpoolcodes .nclient_cpc_mapping_id = a_1.nccp_code ON mastercostpoolcodes .nmaster_cpc_id = clientcostpoolcodes .nmaster_cpc_id ON
Department_1.ndept_id = a_1.ndept_id
WHERE (Department_1.balternate_jointuse_percentage = 'TRUE')
AND (Department_1.ninst_id= p_nInstID)
)AS My
where (ndept_id= p_nDeptID )
ORDER BY My.sdept_name,My.CPCCODE ;
END;
$$ LANGUAGE plpgsql;
I think what you want is the first query to just retrieve the count, store that in your variable, then use that variable in the second query which is the actual source of the result of the function.
So the first query should not use return query but select .. into .. store put the result into the variable.
Then you can prefix the second query with return query to return its result:
CREATE OR REPLACE FUNCTION GetDeptListForViewModifyJointUsePercentages ( p_nInstID numeric,p_nDeptID numeric)
RETURNS Table(
res_ndept_id numeric,
res_salaryPercent character varying,
res_nclient_cpc_mapping_id numeric,
res_CPCCODE character varying,
res_sdept_name character varying,
res_sclient_dept_id character varying,
res_sAlternateJointUsePercentage character varying
)
AS $$
declare
v_AccountTotal numeric(18,2);
BEGIN
-- no RETURN query here!!
select SUM(CAST (coalesce(eam.npayroll_amt, null) AS numeric(18,2)))
into v_accounttotal --<<< store result in variable
FROM Account acct
INNER JOIN employeeaccountmapping eam
ON eam.nacct_id = acct.naccount_id
AND acct.ninst_id =p_nInstID
where acct.ndept_id = p_nDeptID;
-- this is the query that should be returned
RETURN QUERY
SELECT *
FROM (
select dep.ndept_id,
CASE WHEN v_AccountTotal = 0 THEN 0
ELSE Round(SUM(CAST(coalesce(eam.npayroll_amt, null) AS numeric(18,2)) * cac.npercentage_assigned/100) / v_AccountTotal *100,null)
END as salaryPercent,
cac.nclient_cpc_mapping_id,
client.sclient_cpc AS CPCCODE,
dep.sdept_name,
dep.sclient_dept_id,
'NO' AS sAlternateJointUsePercentage
FROM account
INNER JOIN employeeaccountmapping eam
ON eam.nacct_id = account .naccount_id AND account .ninst_id=p_nInstID
INNER JOIN accountcpcmapping acm
ON acm.naccount_cpc_mapping_id = account.naccount_cpc_mapping_id
INNER JOIN cpcaccountcpcmapping as cac
ON cac.naccount_cpc_mapping_id=acm.naccount_cpc_mapping_id
INNER JOIN clientcostpoolcodes as client
ON client.nclient_cpc_mapping_id=cac.nclient_cpc_mapping_id
INNER JOIN mastercostpoolcodes
ON mastercostpoolcodes .nmaster_cpc_id= client.nmaster_cpc_id
INNER JOIN department as dep
ON account.ndept_id=dep.ndept_id and dep.balternate_jointuse_percentage=FALSE
where account.ndept_id =p_nDeptID
Group by dep.ndept_id,cac.nclient_cpc_mapping_id,client.sclient_cpc
,dep.sdept_name,dep.sclient_dept_id, dep.balternate_jointuse_percentage
UNION
SELECT Department_1.ndept_id, a_1.SumByCPC, clientcostpoolcodes.nclient_cpc_mapping_id,
clientcostpoolcodes .sclient_cpc, Department_1.sdept_name, Department_1.sclient_dept_id,
'YES' AS sAlternateJointUsePercentage
FROM department AS Department_1
LEFT OUTER JOIN mastercostpoolcodes --<<< missing join condition !!
RIGHT OUTER JOIN clientcostpoolcodes --<<< missing join condition !!
RIGHT OUTER JOIN (
SELECT JointUseStatistics_1.nccp_code,
SUM(JointUseStatistics_1.npercent) /
(SELECT SUM(jointusestatistics.npercent) AS SumByCPC
FROM jointusestatistics
INNER JOIN roomdepartmentmapping ON jointusestatistics.nroom_allocation_id = roomdepartmentmapping .nroom_allocation_id
WHERE (roomdepartmentmapping .ndept_id = Room_1.ndept_id)) * 100 AS SumByCPC,
Room_1.ndept_id
FROM jointusestatistics JointUseStatistics_1
INNER JOIN roomdepartmentmapping AS Room_1 ON JointUseStatistics_1.nroom_allocation_id = Room_1.nroom_allocation_id
GROUP BY JointUseStatistics_1.nccp_code, JointUseStatistics_1.npercent, Room_1.ndept_id
) AS a_1 ON clientcostpoolcodes.nclient_cpc_mapping_id = a_1.nccp_code
ON mastercostpoolcodes.nmaster_cpc_id = clientcostpoolcodes.nmaster_cpc_id --<< that should be somewhere else
ON Department_1.ndept_id = a_1.ndept_id --<< ??????
WHERE (Department_1.balternate_jointuse_percentage = 'TRUE')
AND (Department_1.ninst_id= p_nInstID)
) AS My
where (ndept_id= p_nDeptID )
ORDER BY My.sdept_name,My.CPCCODE;
END;
$$ LANGUAGE plpgsql;
Note that there are several syntax errors in your second query because the join conditions are scattered around the query. I have tried to highlight them.
In Postgresql, function returns a single value. But in your example, you are trying to return multiple outputs in terms of number of rows and columns.
You can alternatively use a stored procedure and save the output in a temporary table. Later use that table for your use.
I have documents which can belong to several classes and can contain several tokens (words):
create table Tokens (
Id INT not null,
Text NVARCHAR(255) null,
primary key (Id)
)
create table DocumentClassTokens (
Id INT not null,
DocumentFk INT null,
ClassFk INT null,
TokenFk INT null,
primary key (Id)
)
I would like to determine these stats (for all tokens given the class):
A = number of distinct documents which contain token and belong to class
B = number of distinct documents which contain token and do not belong to class
C = number of distinct documents which do not contain token and belong to class
D = number of distinct documents which do not contain token and do not belong to class
I am using this at the moment but it does not look right (I am pretty sure that the computation of A and B is correct):
declare #class int;
select #class = id from dbo.Classes where text = 'bla'
;with A as
(
select
a.text as token,
count(distinct DocumentFk) as A
from dbo.Tokens as a
inner join dbo.DocumentClassTokens as b on a.id = b.TokenFk and b.ClassFk = #class
group by a.text
)
,B as
(
select
a.text as token,
count(distinct DocumentFk) as B
from dbo.Tokens as a
inner join dbo.DocumentClassTokens as b on a.id = b.TokenFk and b.ClassFk != #class
group by a.text
)
,C as
(
select
a.text as token,
count(distinct DocumentFk) as C
from dbo.Tokens as a
inner join dbo.DocumentClassTokens as b on a.id != b.TokenFk and b.ClassFk = #class
group by a.text
)
,D as
(
select
a.text as token,
count(distinct DocumentFk) as D
from dbo.Tokens as a
inner join dbo.DocumentClassTokens as b on a.id != b.TokenFk and b.ClassFk != #class
group by a.text
)
select
case when A is null then 0 else A end as A,
case when B is null then 0 else B end as B,
case when C is null then 0 else C end as C,
case when D is null then 0 else D end as D,
t.Text,
t.id
from dbo.Tokens as t
left outer join A as a on t.text = a.token
left outer join B as b on t.text = b.token
left outer join C as c on t.text = c.token
left outer join D as d on t.text = d.token
order by t.text
Any feedback would be very much appreciated. Many thanks!
Best wishes,
Christian
PS:
Some test data:
use play;
drop table tokens
create table Tokens
(
Id INT not null,
Text NVARCHAR(255) null,
primary key (Id)
)
insert into Tokens (id, text) values (1,'1')
insert into Tokens (id, text) values (2,'2')
drop table DocumentClassTokens
create table DocumentClassTokens (
Id INT not null,
DocumentFk INT null,
ClassFk INT null,
TokenFk INT null,
primary key (Id)
)
insert into DocumentClassTokens (Id,documentfk,ClassFk,TokenFk) values (1,1,1,1)
insert into DocumentClassTokens (Id,documentfk,ClassFk,TokenFk) values (2,1,1,2)
insert into DocumentClassTokens (Id,documentfk,ClassFk,TokenFk) values (3,2,1,1)
insert into DocumentClassTokens (Id,documentfk,ClassFk,TokenFk) values (4,2,2,1)
insert into DocumentClassTokens (Id,documentfk,ClassFk,TokenFk) values (5,3,2,1)
insert into DocumentClassTokens (Id,documentfk,ClassFk,TokenFk) values (6,3,2,3)
Your question seems now much clearer, and if I haven't overlooked anything, then here's a query you might try to run against your data.
DECLARE #class int;
SET #class = 1;
SELECT
TokenFk,
TokenClassDocs AS A,
TokenNonClassDocs AS B,
TotalClassDocs - TokenClassDocs AS C,
TotalNonClassDocs - TokenNonClassDocs AS D
FROM (
SELECT
TokenFk,
COUNT(DISTINCT CASE ClassFk WHEN #class THEN DocumentFk ELSE NULL END) AS TokenClassDocs,
COUNT(DISTINCT CASE ClassFk WHEN #class THEN NULL ELSE DocumentFk END) AS TokenNonClassDocs
FROM DocumentClassTokens dct
GROUP BY dct.TokenFk
) AS bytoken
CROSS JOIN (
SELECT
COUNT(DISTINCT CASE ClassFk WHEN #class THEN DocumentFk ELSE NULL END) AS TotalClassDocs,
COUNT(DISTINCT CASE ClassFk WHEN #class THEN NULL ELSE DocumentFk END) AS TotalNonClassDocs
FROM DocumentClassTokens
) AS totals
Please let us know if it's all right.
EDIT
The above solution is wrong. Here's the fixed one, and it certainly seems correct only I do not like it as much as the wrong version (what an irony...).
DECLARE #class int;
SET #class = 1;
SELECT
TokenFk,
TokenClassDocs AS A,
TokenNonClassDocs AS B,
TotalClassDocs - TokenClassDocs AS C,
TotalNonClassDocs - TokenNonClassDocs AS D
FROM (
SELECT
TokenFk,
COUNT(DISTINCT cls.DocumentFk) AS TokenClassDocs,
COUNT(DISTINCT CASE WHEN cls.DocumentFk IS NULL THEN dct.DocumentFk END) AS TokenNonClassDocs
FROM DocumentClassTokens dct
LEFT JOIN (
SELECT DISTINCT DocumentFk
FROM DocumentClassTokens
WHERE ClassFk = #class
) cls ON dct.DocumentFk = cls.DocumentFk
GROUP BY dct.TokenFk
) AS bytoken
CROSS JOIN (
SELECT
COUNT(DISTINCT cls.DocumentFk) AS TotalClassDocs,
COUNT(DISTINCT CASE WHEN cls.DocumentFk IS NULL THEN dct.DocumentFk END) AS TotalNonClassDocs
FROM DocumentClassTokens dct
LEFT JOIN (
SELECT DISTINCT DocumentFk
FROM DocumentClassTokens
WHERE ClassFk = #class
) cls ON dct.DocumentFk = cls.DocumentFk
) AS totals
Note: I think I can see now how you can check if the figures are wrong: the sum of A, B, C, D in every row (i.e. for every token) must be equal to the total document count, which should not be surprising, because every document can satisfy 1 and only 1 of the 4 cases being explored. If the row sum is different from the total document count then some figures in the row are certainly wrong.
This seams to do what you want by your description. Looking at your code, I'm not so sure.
Edit 1 With columns instead of rows and #ClassID as filter.
declare #ClassID int
set #ClassID = 1
;with cte(DokumentFk, TokenFk, ClassFk) as
(
select DocumentFk, max(TokenFK), max(ClassFk)
from DocumentClassTokens
where ClassFK = #ClassID
group by DocumentFK
)
select
(select count(*)
from cte
where
TokenFk is not null and
ClassFk is not null) as A,
(select count(*)
from cte
where
TokenFk is not null and
ClassFk is null) as B,
(select count(*)
from cte
where
TokenFk is null and
ClassFk is not null) as C,
(select count(*)
from cte
where
TokenFk is null and
ClassFk is null) as D
I am trying to develop a T-SQL query to exclude all rows from another table "B". This other table "B" has 3 columns comprising its PK for a total of 136 rows. So I want to select all columns from table "A" minus those from table "B". How do I do this? I don't think this query is correct because I am still getting a duplicate record error:
CREATE TABLE #B (STUDENTID VARCHAR(50), MEASUREDATE SMALLDATETIME, MEASUREID VARCHAR(50))
INSERT #B
SELECT studentid, measuredate, measureid
from [J5C_Measures_Sys]
GROUP BY studentid, measuredate, measureid
HAVING COUNT(*) > 1
insert into J5C_MasterMeasures (studentid, measuredate, measureid, rit)
select A.studentid, A.measuredate, B.measurename+' ' +B.LabelName, A.score_14
from [J5C_Measures_Sys] A
join [J5C_ListBoxMeasures_Sys] B on A.MeasureID = B.MeasureID
join sysobjects so on so.name = 'J5C_Measures_Sys' AND so.type = 'u'
join syscolumns sc on so.id = sc.id and sc.name = 'score_14'
join [J5C_MeasureNamesV2_Sys] v on v.Score_field_id = sc.name
where a.score_14 is not null AND B.MEASURENAME IS NOT NULL
and (A.studentid NOT IN (SELECT studentid from #B)
and a.measuredate NOT IN (SELECT measuredate from #B)
and a.measureid NOT IN (SELECT measureid from #B))
use NOT EXISTS...NOT IN doesn't filter out NULLS
insert into J5C_MasterMeasures (studentid, measuredate, measureid, rit)
select A.studentid, A.measuredate, B.measurename+' ' +B.LabelName, A.score_14
from [J5C_Measures_Sys] A
join [J5C_ListBoxMeasures_Sys] B on A.MeasureID = B.MeasureID
join sysobjects so on so.name = 'J5C_Measures_Sys' AND so.type = 'u'
join syscolumns sc on so.id = sc.id and sc.name = 'score_14'
join [J5C_MeasureNamesV2_Sys] v on v.Score_field_id = sc.name
where a.score_14 is not null AND B.MEASURENAME IS NOT NULL
AND NOT EXISTS (select 1 from #B where #b.studentid = A.studentid
and a.measuredate = #B.measuredate
and a.measureid = #B.measureid)
and not exists (select 1 from J5C_MasterMeasures z
where z.studentid = A.studentid)
Just so you know, take a look at Select all rows from one table that don't exist in another table
Basically there are at least 5 ways to select all rows from onr table that are not in another table
NOT IN
NOT EXISTS
LEFT and RIGHT JOIN
OUTER APLY (2005+)
EXCEPT (2005+)
Here is a general solution for the difference operation using left join:
select * from FirstTable
left join SecondTable on FirstTable.ID = SecondTable.ID
where SecondTable.ID is null
Of course yours would have a more complicated join on clause, but the basic operation is the same.
I think you can use "NOT IN" with a subquery, but you say you have a multi-field key?
I'd be thinking about using a left outer join and then testing for null on the right...
Martin.
I am trying to develop a query to just return non-duplicate records so that I can add these to my database, but I keep getting the duplicate record error.
I tried your solution but am still getting duplicate error problem. I deleted the 35 rows which were duplicate. What else could be causing this? Here is my query. Part of the confusion I think is that measureid is a single column in j5c_MasterMeasures, but this value comes from two fields in j5c_ListBoxMeasures_Sys.
CREATE TABLE #GOOD_RECORDS3 (STUDENTID VARCHAR(50), MEASUREDATE SMALLDATETIME, MEASUREID VARCHAR(100),
score_10 VARCHAR(100))
INSERT INTO #GOOD_RECORDS3
select A.studentid, A.measuredate, B.measurename+' ' +B.LabelName, A.score_10
from [J5C_Measures_Sys] A join [J5C_ListBoxMeasures_Sys] B on A.MeasureID = B.MeasureID
except
select A.studentid, A.measuredate, B.measurename+' ' +B.LabelName, A.score_10
from [J5C_Measures_Sys] A join [J5C_ListBoxMeasures_Sys] B on A.MeasureID = B.MeasureID
GROUP BY A.studentid, A.measuredate, B.measurename, B.LabelName, A.score_10
having COUNT(A.score_10) > 1
delete #GOOD_RECORDS3
from #GOOD_RECORDS3 a
join sysobjects so on so.name = 'J5C_Measures_Sys' AND so.type = 'u'
join syscolumns sc on so.id = sc.id and sc.name = 'score_10'
join [J5C_MeasureNamesV2_Sys] v on v.Score_field_id = sc.name
WHERE A.SCORE_10 IS NOT NULL AND A.STUDENTID IS NOT NULL AND A.MEASUREID IS NOT NULL
and exists (select 1 from J5C_MasterMeasures M
where M.StudentID = A.StudentID
and M.MeasureID = A.MeasureID)
Insert into J5C_MasterMeasures (studentid, measuredate, measureid, nce)
select A.studentid, A.measuredate, a.MEASUREID, A.score_10
from #GOOD_RECORDS3 a
join sysobjects so on so.name = 'J5C_Measures_Sys' AND so.type = 'u'
join syscolumns sc on so.id = sc.id and sc.name = 'score_10'
join [J5C_MeasureNamesV2_Sys] v on v.Score_field_id = sc.name
WHERE A.SCORE_10 IS NOT NULL AND A.STUDENTID IS NOT NULL AND A.MEASUREID IS NOT NULL
You have not menstioned the specifics of the unique constraint on J5C_MasterMeasures. Therefore, I assumed that all four columns being inserted were part of the constraint. In addition, your use of Except leads me to believe that you are using SQL Server 2005 or later. In addition, it is not clear how the join to J5C_MeasureNamesV2_Sys fits into the design or solution.
With GoodRecords As
(
Select A.StudentId
, A.measuredate
, B.measurename+ ' ' +B.LabelName
, A.score_10 As NCE
From [J5C_Measures_Sys] A
Join [J5C_ListBoxMeasures_Sys] B
On A.MeasureID = B.MeasureID
Where A.StudentId Is Not Null
And A.Score_10 Is Not Null
And A.MeasureId Is Not Null
Group By A.StudentId
, A.MeasureDate
, B.MeasureName+ ' ' +B.LabelName
, A.score_10
Having Count(A.Score_10) = 0
)
Insert J5C_MasterMeasures ( StudentId, MeasureData, MeasureId, NCE )
Select GR.StudentId, GR.MeasureData, GR.MeasureId, GR.NCE
From GoodRecords As GR
Join [J5C_MeasureNamesV2_Sys] v
On v.Score_field_id = 'Score_10'
Where Not Exists (
Select 1
From J5C_MasterMeasures As J1
Where J1.StudentId = GR.StudentId
And J1.MeasureData = GR.MeasureData
And J1.MeasureId = GR.MeasureId
And J1.NCE = GR.NCE
)