IIF Statement help - SUM OF value greater than or equal to - sql

I am stuck and need advice.
This may be something simple, however, I am a beginner here and trying to learn as quickly as possible, so please bear with me.
I have a table containing attendance data in "A" / "P" format. I am trying to show in a report how many people within a class have missed three or more times with a date range. For the most part I have the SQL statement doing all of the work with one exception. I can show a sum for how many times someone has missed, but I cannot figure out how to only show students with greater than 3 absences.
I am entering the following in an expression on the column I want the data to return in:
=SUM(IIF(Fields!Attendance.Value ="A",1,NOTHING))
If I write the expression like this:
=SUM(IIF(Fields!Attendance.Value ="A",1,NOTHING))>=3
I get TRUE/FALSE returns. That would be ok if I could then figure out how to only shows the TRUE returns.
Any advice is appreciated!
My entire SQL statement - there are two other datasets that get called to pull data into this one.
SELECT smgp_group.group_id
, smgp_group.group_name
, core_v_person_basic.last_name + ', ' + core_v_person_basic.nick_name as Name
, core_v_person_basic.birth_date AS Birthdate
, '*' + CONVERT(varchar, core_v_person_basic.person_id) + '*' AS person_id
, core_v_person_basic.street_address_1
, core_v_person_basic.city + ',' + core_v_person_basic.state + ' ' + core_v_person_basic.postal_code AS Citystatezip
, core_v_person_basic.home_phone
, core_v_person_basic.email
, core_lookup.lookup_value AS [Group Role]
, CATD.occurrence_end_time
, CATD.Attendance as attendance
, MAX(CATD.DateLastAttended) AS Datelastattended
, CATD.occurrence_end_time AS [Start Date]
, CATD.occurrence_end_time AS [End Date]
, '*$' + CONVERT(varchar, CATD.occurrence_id) + '*' AS 'occurrence_id'
, core_v_person_basic.cell_phone
FROM smgp_group
INNER JOIN cust_v_attendanceroll AS CATD
INNER JOIN core_lookup ON CATD.role_luid = core_lookup.lookup_id
INNER JOIN core_v_person_basic ON CATD.person_id = core_v_person_basic.person_id ON smgp_group.group_id = CATD.group_id
where CATD.occurrence_end_time between #startdate AND #enddate and smgp_group.group_id IN (#group)
GROUP BY smgp_group.group_id, smgp_group.group_name, core_v_person_basic.last_name,core_v_person_basic.nick_name, core_v_person_basic.birth_date, core_v_person_basic.street_address_1,
core_v_person_basic.city + ',' + core_v_person_basic.state + ' ' + core_v_person_basic.postal_code, core_v_person_basic.home_phone,
core_v_person_basic.email, core_lookup.lookup_value, CATD.occurrence_end_time, CATD.Attendance, CATD.occurrence_id, core_v_person_basic.person_id,
core_v_person_basic.cell_phone
HAVING attendance = 'A'
ORDER BY attendance

Want to give this a try?
SideTrack: You might want to check:
Both [Start Date] and [End Date] are set to CATD.occurrence_end_time
SELECT *
FROM (
SELECT smgp_group.group_id
, smgp_group.group_name
, core_v_person_basic.last_name + ', ' + core_v_person_basic.nick_name as Name
, core_v_person_basic.birth_date AS Birthdate
, '*' + CONVERT(varchar, core_v_person_basic.person_id) + '*' AS person_id
, core_v_person_basic.street_address_1
, core_v_person_basic.city + ',' + core_v_person_basic.state + ' ' + core_v_person_basic.postal_code AS Citystatezip
, core_v_person_basic.home_phone
, core_v_person_basic.email
, core_lookup.lookup_value AS [Group Role]
, CATD.occurrence_end_time
, MAX(CATD.DateLastAttended) AS Datelastattended
, CATD.occurrence_end_time AS [Start Date]
, CATD.occurrence_end_time AS [End Date]
, '*$' + CONVERT(varchar, CATD.occurrence_id) + '*' AS 'occurrence_id'
, core_v_person_basic.cell_phone
, COUNT(*) AS absentCount
FROM smgp_group
INNER JOIN cust_v_attendanceroll AS CATD
INNER JOIN core_lookup ON CATD.role_luid = core_lookup.lookup_id
INNER JOIN core_v_person_basic ON CATD.person_id = core_v_person_basic.person_id ON smgp_group.group_id = CATD.group_id
WHERE CATD.occurrence_end_time BETWEEN #startdate AND #enddate
AND smgp_group.group_id IN (#group)
AND CATD.Attendance = 'A'
GROUP BY smgp_group.group_id, smgp_group.group_name, core_v_person_basic.last_name,core_v_person_basic.nick_name, core_v_person_basic.birth_date, core_v_person_basic.street_address_1,
core_v_person_basic.city + ',' + core_v_person_basic.state + ' ' + core_v_person_basic.postal_code, core_v_person_basic.home_phone,
core_v_person_basic.email, core_lookup.lookup_value, CATD.occurrence_end_time, CATD.occurrence_id, core_v_person_basic.person_id,
core_v_person_basic.cell_phone
) AS tblSource
WHERE absentCount>=3

Related

Simplify Query to be used as dataset in winform rdlc report

I am trying to have this query populate a reportviewer in a winform app I am building (and will change parameters in query to values selected on form before populating report to be viewed). But the over function is not able to work. User will enter parameters from radio boxes, drop down lists etc, click search and reportviewer will open so they can print. Query is very ugly , and i have been working on it for some time. Its the only way i could get resultset in desired format.
SQL QUERY looking for help on to shorten with same results
DECLARE #EndReport DATETIME, #StartReport DATETIME, #Location INT, #Department varchar(50)
SET #EndReport = '10-15-2018' SET #StartReport = '10-15-2018' SET #Department = 'fb' SET #Location = 10
SELECT row_number() over (order by (ai.FirstName + ' ' + ai.LastName)) RowNum
,AssociateName = isnull(upper(ai.FirstName + ' ' + ai.LastName),'**' + cast(t.ID as varchar(30)) + '**')
,ID = t.ID
,Codes = (t.DeptCode + '-' + t.OpCode)
,TimeSUM = cast(SUM(datediff(second,StartTime, FinishTime) /3600.0) as decimal (6,2))
,Units = SUM(Units)
,UPH = cast(isnull(sum(Units) / nullif(sum(datediff(minute,StartTime,FinishTime))*1.0,0),0.0)*60 as decimal(10,0))
into temptable10
FROM TimeLogNEW t LEFT JOIN AssociateInfo ai
ON t.ID = ai.ID
JOIN GoalSetUp g
ON (t.DeptCode + '-' + t.OpCode) = (g.DeptCode + '-' + g.OpCode)
WHERE EventDate between #StartReport and #EndReport
and t.Location = #Location and g.location= #Location and ((t.DeptCode + t.OpCode) in (g.DeptCode + g.OpCode)) and t.DeptCode = #Department
GROUP BY t.DeptCode,t.OpCode,ai.FirstName,ai.LastName, t.ID
SELECT
[Associate Name] = AssociateName
,[Codes] = Codes
,[TimeSUM] = TimeSUM
,[Units] = Units
,[UPH] = UPH
,[UPH Target] = Goal
,[Actual %] = CASE WHEN goal = 0 then '0%'
else convert(varchar,cast(100* (isnull(UPH,0)/nullif(Goal,0)) as decimal(10,0))) + '%' END
FROM goalsetup g join temptable10 on g.DeptCode = left(codes,2)and g.opcode = RIGHT(codes,2)
WHERE g.Location = #Location
ORDER BY Codes, UPH Desc
drop table temptable10
SQL Resultset
Visual Studio error
Adding visual studio screenshots. Updated after answer below
I cannot know if this works, because I have no tables to test with. (i.e. If it errors you will have to decide what to do.)
there is no obvious reason for the row_number() column, so I removed it
Codes = (t.DeptCode + '-' + t.OpCode) when making the table, followed by:
join temptable10 on g.DeptCode = left(codes,2)and g.opcode = RIGHT(codes,2)
that is inefficient, and unnecessary, just keep both columns
in fact a lot of concatenation of dept & op codes occurs which seems unnecessary, just use the 2 columns without all that extra effort.
between is a dog when used for date ranges, I strongly suggest using what I have in the query below. This date range construct of >= with < (+1 day) works for all date/time data types
please use table aliases when referencing any column, a reader such as myself cannot know which table some of those columns come from, making it way harder to debug/maintain.
Suggested query:
DECLARE #EndReport datetime
, #StartReport datetime
, #Location int
, #Department varchar(50)
SET #EndReport = '10-15-2018'
SET #StartReport = '10-15-2018'
SET #Department = 'fb'
SET #Location = 10
SELECT
AssociateName = ISNULL(UPPER(ai.FirstName + ' ' + ai.LastName), '**' + CAST(t.ID AS varchar(30)) + '**')
, ID = t.ID
, Codes = (t.DeptCode + '-' + t.OpCode)
, t.DeptCode
, t.OpCode
, TimeSUM = CAST(SUM(DATEDIFF(SECOND, StartTime, FinishTime) / 3600.0) AS decimal(6, 2))
, Units = SUM(Units)
, UPH = CAST(ISNULL(SUM(Units) / NULLIF(SUM(DATEDIFF(MINUTE, StartTime, FinishTime)) * 1.0, 0), 0.0) * 60 AS decimal(10, 0))
INTO temptable10
FROM TimeLogNEW t
LEFT JOIN AssociateInfo ai
ON t.ID = ai.ID
JOIN GoalSetUp g
ON t.DeptCode = g.DeptCode AND t.OpCode = g.OpCode
WHERE EventDate >= #StartReport AND EventDate < dateadd(day,1,#EndReport)
AND t.Location = #Location
AND g.location = #Location
AND t.DeptCode = #Department
GROUP BY
t.DeptCode
, t.OpCode
, ai.FirstName
, ai.LastName
, t.ID
SELECT
[Associate Name] = t10.AssociateName
, [Codes] = t10.Codes
, [TimeSUM] = t10.TimeSUM
, [Units] = t10.Units
, [UPH] = t10.UPH
, [UPH Target] = g.Goal
, [Actual %] =
CASE
WHEN g.goal = 0 THEN '0%'
ELSE CONVERT(varchar, CAST(100 * (ISNULL(t10.UPH, 0) / NULLIF(g.Goal, 0)) AS decimal(10, 0))) + '%'
END
FROM goalsetup g
JOIN temptable10 t10
ON g.DeptCode = t10.DeptCode
AND g.opcode = t10.opcode
WHERE g.Location = #Location
ORDER BY
t10.Codes
, t10.UPH DESC
DROP TABLE temptable10

query gives an error saying there's an issue with converting a value to integer

I have a query where I do multiple joins to get the text values for some of my fields. The problem is I keep getting an error stating that
Conversion failed when converting the varchar value '1774.14 ' to data
type int.
Below is my query...
SELECT t1.changedon as [Changed On], t1.fldname as [Field Name],
CASE WHEN (t1.Fldname='LastKnownProvider' and t1.oldValue > 1000) THEN coalesce((t4.ProviderName + ' (' + t4.ProviderAddress + ', ' + t4.ProviderCity + ')'),cast(t1.oldvalue as varchar)) ELSE coalesce(t2.label,cast(t1.oldvalue as varchar)) END as [Old Value],
CASE WHEN (t1.Fldname='LastKnownProvider' and t1.newValue > 1000) THEN coalesce((t5.ProviderName + ' (' + t5.ProviderAddress + ', ' + t5.ProviderCity + ')'),cast(t1.Newvalue as varchar)) ELSE coalesce(t3.label, cast(t1.NewValue as varchar)) END as [New Value]
CASE WHEN t1.Changedfrom ='Upload' THEN 'UPLOAD' ELSE 'manual' END AS [Upload/Manual]
FROM tblFieldChanges t1
LEFT JOIN tblReferenceData t2 on t1.oldvalue=cast(t2.id as varchar)
LEFT JOIN tblReferenceData t3 on t1.newValue=cast(t3.id as varchar)
left join tblProviders t4 on t1.oldvalue = cast(t4.ProviderID as varchar)
left join tblProviders t5 on t1.NewValue = cast(t5.ProviderID as varchar)
WHERE TblName = 'tblClients' AND PKID = 8558
My tblFieldChanges tables looks like this...
This tables contains data from field changes that had occurred on update, so a sample data might look like this...
ID tblName FldName PKID Oldvalue NewValue ChangedOn
17 tblClients Cost 19 1774.14 1775.19 7/21/2017 8:45am
The other table names, mainly tblReferenceData and tblProviders both have an ID and a text Value that I grab (especially tblReferenceData). Anyone know why I might be getting an error. It seems that it doesn't only error out on a number as is the case in the error, but also, if I have a text value such as city (San Francisco) I get a similar error stating that Conversion failed when converting the varchar value 'San Francisco' to data type int.
Any help is much appreciated.
Since OP has stated that the data type cannot be changed. Here is the solution by casting the OldValue and NewValue values to decimal before doing a comparison:
SELECT t1.changedon as [Changed On], t1.fldname as [Field Name],
CASE WHEN (t1.Fldname='LastKnownProvider' and CAST(t1.oldValue AS DECIMAL(19,2)) > 1000) THEN coalesce((t4.ProviderName + ' (' + t4.ProviderAddress + ', ' + t4.ProviderCity + ')'),cast(t1.oldvalue as varchar)) ELSE coalesce(t2.label,cast(t1.oldvalue as varchar)) END as [Old Value],
CASE WHEN (t1.Fldname='LastKnownProvider' and CAST(t1.newValue AS DECIMAL(19,2)) > 1000) THEN coalesce((t5.ProviderName + ' (' + t5.ProviderAddress + ', ' + t5.ProviderCity + ')'),cast(t1.Newvalue as varchar)) ELSE coalesce(t3.label, cast(t1.NewValue as varchar)) END as [New Value]
CASE WHEN t1.Changedfrom ='Upload' THEN 'UPLOAD' ELSE 'manual' END AS [Upload/Manual]
FROM tblFieldChanges t1
LEFT JOIN tblReferenceData t2 on t1.oldvalue=cast(t2.id as varchar)
LEFT JOIN tblReferenceData t3 on t1.newValue=cast(t3.id as varchar)
left join tblProviders t4 on t1.oldvalue = cast(t4.ProviderID as varchar)
left join tblProviders t5 on t1.NewValue = cast(t5.ProviderID as varchar)
WHERE TblName = 'tblClients' AND PKID = 8558
This can also be done by using a string comparison, but this is a very bad practice:
t1.oldValue > '1000'

SQL OpenQuery - Escaping Quotes

Been trying for some hours to convert this to a query I can use with OPENQUERY in SQL Server 2014 (to use with Progress OpenEdge 10.2B via ODBC). Can't seem to get the escaping of the quote right. Can anyone offer some assistance? Is there a tool to do it?
(There's a SQL table called #tAPBatches that is used in this, but I omitted it from this code)
DECLARE
#NoDays AS INT = 30
,#Prefix AS VARCHAR(5) = 'M_AP_'
SELECT
#Prefix + LTRIM(CAST(gh.[Batch-Number] AS VARCHAR(20))) AS BatchNo
,gh.[Batch-Number] AS BatchNo8
, aph.[Reference-number] AS InvoiceNo
,aph.[Voucher-Number] AS VoucherNo
,aph.[Amount] AS InvoiceTotal
,gh.[Journal-Number] AS JournalNo
,4 AS FacilityID
,CASE aph.[voucher-type]
WHEN 'DM' THEN 5
ELSE 1
END AS DocType
,apb.[Batch-Desc] AS BatchDesc
,apb.[Posting-Date] AS PostingDate
,apb.[Posting-Period]
,apb.[Posting-Fiscal-Year]
,apb.[Batch-Status]
,apb.[Expected-Count]
,apb.[Expected-Amount]
,apb.[Posted-To-GL-By]
,'Broadview' AS FacilityName
,apb.[Date-Closed] AS BatchDate
,gh.[Posted-by] AS PostUser
,gh.[Posted-Date] AS PostDT
,gh.[Created-Date] AS CreateDT
,gh.[Created-By] AS CreateUser
,aph.[Supplier-Key] AS VendorID
,sn.[Supplier-Name]
,aph.[Invoice-Date] AS InvoiceDate
,-1 AS Total
,-1 AS Discount
,gh.[Posted-by] AS Username
,CASE gt.[Credit-Debit]
WHEN 'CR' THEN LEFT(CAST(gacr.[GL-Acct] AS VARCHAR(20)), 2) + '.' + SUBSTRING(CAST(gacr.[GL-Acct] AS VARCHAR(20)), 3, 6) + '.'
+ RIGHT(CAST(gacr.[GL-Acct] AS VARCHAR(20)), 3)
ELSE NULL
END AS GLCreditAcct
,CASE gt.[Credit-Debit]
WHEN 'DR' THEN LEFT(CAST(gacr.[GL-Acct] AS VARCHAR(20)), 2) + '.' + SUBSTRING(CAST(gacr.[GL-Acct] AS VARCHAR(20)), 3, 6) + '.'
+ RIGHT(CAST(gacr.[GL-Acct] AS VARCHAR(20)), 3)
ELSE NULL
END AS GLDebitAcct
,CASE gt.[Credit-Debit]
WHEN 'CR' THEN gacr.[Report-Label]
ELSE NULL
END AS GLCreditDesc
,CASE gt.[Credit-Debit]
WHEN 'DR' THEN gacr.[Report-Label]
ELSE NULL
END AS GLDebitDesc
,'D' AS [Status]
,aph.[PO-Number] AS PoNo
,aph.[Terms-Code] AS TermsCode
,aph.[Due-Date] AS DueDate
,'' AS Comments
,aph.[Discount-Date] AS DiscountDate
,aph.[Discount-Amount] AS DiscountAmount
,aph.[Discount-Taken] AS DiscountTaken
,aph.[Amount] AS APAmount
,gt.[Amount]
,'BA REGULAR ' AS CheckBookID --ToDO
,0 AS Transferred
,aph.[voucher-type] AS VoucherType
,gt.[Credit-Debit]
,gacr.[Account-type]
,aph.[Freight-Ref-Num]
FROM
[Progress].[GAMS1].pub.[GL-Entry-Header] gh
INNER JOIN [Progress].[GAMS1].pub.[gl-entry-trailer] gt ON gt.[System-ID] = gh.[System-ID] AND gt.[Origin] = gh.[Origin] AND gt.[Journal-Number] = gh.[Journal-Number]
INNER JOIN [Progress].[GAMS1].pub.[apinvhdr] aph ON (gh.[Journal-Number] = aph.[Journal-Number]
OR (gh.[Journal-Num-Reversal-Of] = aph.[Journal-Number] AND aph.[Journal-Number] <> ' ' AND gh.[Journal-Num-Reversal-Of] <> ' '))
AND gh.[system-id] = aph.[system-id-gl]
AND gh.origin = 'inv'
AND gh.[system-id] = 'arcade'
INNER JOIN [Progress].[GAMS1].pub.[APInvoiceBatch] apb ON gh.[Batch-number] = apb.[Batch-number]
AND apb.[system-id] = 'lehigh'
AND apb.[Posted-To-GL] = 1
INNER JOIN [Progress].[GAMS1].pub.[GL-accts] gacr ON gacr.[system-id] = gt.[system-id]
AND gacr.[Gl-Acct-Ptr] = gt.[GL-Acct-Ptr]
INNER JOIN [Progress].[GAMS1].pub.[suppname] sn ON sn.[Supplier-Key] = aph.[Supplier-Key]
AND sn.[system-id] = 'arcade'
WHERE
gh.[Posted-Date] > CAST(DATEADD(DAY, -#NoDays, GETDATE()) AS DATE)
AND case
when CAST(gh."Posting-Period" as int) < 10 then gh."Posting-Year" + '0' + ltrim(gh."Posting-Period")
else gh."Posting-Year" + Ltrim(gh."Posting-Period")
end > '201501'
AND gh.[Batch-number] NOT IN (SELECT
BatchNo COLLATE SQL_Latin1_General_CP1_CI_AS
FROM
#tAPBatches)
TIA
MArk
Here's an example of what's giving me a syntax error. This works, but "M_AP_" is a parameter passed to SP
DECLARE
#NoDays AS INT = 5
,#Prefix AS VARCHAR(5) = 'M_AP_';
DECLARE
#InterestDate AS varchar(20)
SELECT #InterestDate = CAST(CAST(DATEADD(DAY, -#NoDays, GETDATE()) AS DATE) AS VARCHAR(20))
SELECT * FROM OPENQUERY(PROGRESS,
'SELECT TOP 100 ''M_AP_'' + LTRIM(CAST(gh."Batch-Number" AS VARCHAR(20))) AS BatchNo
, gh."Batch-Number"
This works, but when I try to swap in the variable I get Incorrect Syntax near '+'
DECLARE
#NoDays AS INT = 5
,#Prefix AS VARCHAR(5) = 'M_AP_';
DECLARE
#InterestDate AS varchar(20)
SELECT #InterestDate = CAST(CAST(DATEADD(DAY, -#NoDays, GETDATE()) AS DATE) AS VARCHAR(20))
SELECT * FROM OPENQUERY(PROGRESS,
'SELECT TOP 100 '' ' + #Prefix + ' '' + LTRIM(CAST(gh."Batch-Number" AS VARCHAR(20))) AS BatchNo
, gh."Batch-Number"
FROM
"GAMS1".pub."GL-Entry-Header" gh
OPENQUERY will only support a string literal query that is less than 8K. You might be running into that limit if you've got even more code that you're not showing here. Make sure that your query is less than 8000 bytes, or create procedures or views to reduce the size of your query.
It only accepts a single string literal... so if you are trying to concatenate strings and parameters together, it will not work. There are some ways to work around this by using dynamic SQL or creating supporting tables or views for filters.

Conversion failed when converting the nvarchar value '29449,29446,29450,29534' to data type int

I am create a stored procedure in SQL and I get the following error when I execute the query:
Conversion failed when converting the nvarchar value '11021,78542,12456,24521' to data type int.
Any idea why?
SELECT
A.Art_ID, A.Title
FROM
Art A
INNER JOIN
Iss I ON A.Iss_ID = I.Iss_ID
INNER JOIN
Sections S ON A.Section_ID = S.Section_ID
INNER JOIN
iPadSec IPS ON A.Sec_ID = IPS.Sec_ID
WHERE
A.Art_ID IN (SELECT CAST(Art_IDs AS int) /***error happens here***/
FROM Book_Art b
WHERE Sub_ID = 68)
AND I.Iss > dateadd(month, -13, getdate())
AND A.Active = 1
AND IPS.Active = 1
AND A.PDate <= getdate()
ORDER BY
PDate DESC, Art_ID DESC;
You cannot do what you want using in. First, it is a really bad idea to store ids in lists in strings. You should be using a junction table.
That said, sometimes this is necessary. You can rewrite this line of code as:
EXISTS (SELECT 1 /***error happens here***/
FROM Book_Art b
WHERE Sub_ID = 68 AND
',' + Art_IDs + ',' LIKE '%,' + cast(A.Art_ID as varchar(255)) + ',%'
)
However, the performance would generally be on the lousy side and there is little prospect of speeding this up without fixing the data structure. Use a junction table instead of a string to store lists.
Adding this line works for me.
declare #ids varchar(1000)
select #ids = art_ids from book_art where sub_id = #Sub_ID
EXECUTE ( 'SELECT A.Art_ID, A.Title'
+ ' FROM Art A'
+ ' INNER JOIN Iss I ON A.Iss_ID = I.Iss_ID'
+ ' INNER JOIN Sections S ON A.Section_ID = S.Section_ID'
+ ' INNER JOIN iPadSec IPS ON A.Sec_ID = IPS.Sec_ID'
+ ' WHERE A.Art_ID IN (' + #ids + ')'
+ ' AND I.Iss > dateadd(month, -13, getdate())'
+ ' AND A.Active = 1'
+ ' AND IPS.Active = 1'
+ ' AND A.PDate <= getdate()'
+ ' ORDER BY PDate DESC,'
+ ' Art_ID DESC;'
)
END
Thank you all for your help :)

Using Group By Clause in Stored procedure

I have a storedprocedure in which iam getting InvoiceValue as one field.I have different invoice values corresponding to 1 fileid.I want to get the sum of invoice values corresponding to each fileid.How can i use group by here?
here is my stored procedure
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
ALTER Procedure [dbo].[rptGGM]
(
#FromDate varchar(50),
#ToDate varchar(50),
#PartyID int,
#WID int
)
As
DECLARE #WhereStr VarChar(800)
SET #FromDate = LTRIM(RTRIM(#FromDate))
SET #ToDate = LTRIM(RTRIM(#ToDate))
SET #WhereStr =
CASE #WID
WHEN 23 THEN 'WHERE G.PartyID='+LTRIM(str(#PartyID)) +' AND ((D.ATASea >='''+#FromDate+''' And D.ATASea<='''+#ToDate+'''))'
WHEN 7 THEN 'WHERE G.PartyID='+LTRIM(str(#PartyID)) +' AND ((D.ATASea >='''+#FromDate+''' And D.ATASea<='''+#ToDate+''')) AND A.WorkID='+LTRIM(str(#WID))
WHEN 6 THEN 'WHERE G.PartyID='+LTRIM(str(#PartyID)) +' AND ((D.ATASea >='''+#FromDate+''' And D.ATASea<='''+#ToDate+''')) AND A.WorkID='+LTRIM(str(#WID))
WHEN 11 THEN 'WHERE G.PartyID='+LTRIM(str(#PartyID)) +' AND ((D.ATASea >='''+#FromDate+''' And D.ATASea<='''+#ToDate+''')) AND A.WorkID='+LTRIM(str(#WID))
WHEN 12 THEN 'WHERE G.PartyID='+LTRIM(str(#PartyID)) +' AND ((D.ATASea >='''+#FromDate+''' And D.ATASea<='''+#ToDate+''')) AND A.WorkID='+LTRIM(str(#WID))
END
BEGIN
exec
('SELECT
A.FileNumber As [File_No],
H.IDFNumber as [IDF No],
H.IDFRegNo as [TZDAR],
F.POString As [PO_Numbers],
B.PartyName As [Exporter Name],
F.SIString As [Supplier Invoices],
C.CargoDesc As [Cargo_Description],
dbo.PackCntDetails(A.FileID) As [Pk/Cnt_Details],
D.VesselName As [Vessel Name],
D.VoyageNo As [Voyage No],
L.Amount As [Invoice Value],
convert(varchar, Dbo.ActualDate(A.ETA), 103) + '' '' + convert(varchar, Dbo.ActualDate(A.ETA), 108) As ETA,
convert(varchar,Dbo.ActualDate(D.ATASea),103) + '' '' + convert(varchar, Dbo.ActualDate(D.ATASea), 108) As ATA,
convert(varchar,Dbo.ActualDate(H.PCVRIssuedDate),103) + '' '' + convert(varchar, Dbo.ActualDate(H.PCVRIssuedDate), 108) as [PCVR Issued Date],
convert(varchar,Dbo.ActualDate(V.VATRelDate),103) + '' '' + convert(varchar, Dbo.ActualDate(V.VATRelDate), 108) as [VR Requested],
convert(varchar,Dbo.ActualDate(V.OriginalRecdDate),103) + '' '' + convert(varchar, Dbo.ActualDate(V.OriginalRecdDate), 108) as [VR Granted],
convert(varchar,Dbo.ActualDate(H.SBECVRAppReturnedDate),103) + '' '' + convert(varchar, Dbo.ActualDate(H.SBECVRAppReturnedDate), 108) as [SBE _VR App. ReturnedDate],
convert(varchar,Dbo.ActualDate(H.SBECVRIssuedDate),103) + '' '' + convert(varchar, Dbo.ActualDate(H.SBECVRIssuedDate), 108) as [SBE_CVR IssuedDate],
convert(varchar,Dbo.ActualDate(I.CDFLodgedDate),103) + '' '' + convert(varchar, Dbo.ActualDate(I.CDFLodgedDate), 108) as [CDF LodgedDate],
convert(varchar,dbo.ActualDate(I.AssessmentPaidDate), 103) + '' '' + convert(varchar,dbo.ActualDate(I.AssessmentPaidDate),108) As [DutyPaidDate],
convert(varchar,Dbo.ActualDate(I.EntryLodgedDate),103) + '' '' + convert(varchar, Dbo.ActualDate(I.EntryLodgedDate), 108) as [Entry LodgedDate],
convert(varchar,Dbo.ActualDate(I.EntryPassedDate),103) + '' '' + convert(varchar, Dbo.ActualDate(I.EntryPassedDate), 108) as [Custom Released],
[Actual Days from ATA to CR]=DATEDIFF(dd, Dbo.ActualDate(D.ATASea),Dbo.ActualDate(I.EntryPassedDate)),
convert(varchar,Dbo.ActualDate(K.ShippingLineReleaseDate),103) + '' '' + convert(varchar, Dbo.ActualDate(K.ShippingLineReleaseDate),108) as [ShippingLine ReleaseDate],
convert(varchar,Dbo.ActualDate(K.PortInvoicePaidDate),103) + '' '' + convert(varchar, Dbo.ActualDate(K.PortInvoicePaidDate),108) as [Port_Charges Paid_Date],
convert(varchar,Dbo.ActualDate(K.RemPortYardDateSea),103) + '' '' + convert(varchar, Dbo.ActualDate(K.RemPortYardDateSea),108) as [Rem_Sea_Port to Yard_Date],
[Actual Days From CR to RFD Dar]=DATEDIFF(dd,Dbo.ActualDate(I.EntryPassedDate), Dbo.ActualDate(K.RemPortYardDateSea)),
[Total No: of Days(ATA-RFD)]=DATEDIFF(dd,Dbo.ActualDate(D.ATASea), Dbo.ActualDate(K.RemPortYardDateSea)),
A.Remarks As [File Status]
FROM
FileMain A
INNER JOIN Party G ON G.PartyID = A.PartyID
LEFT JOIN Party B ON B.PartyID = A.ExporterID
LEFT JOIN Cargo C ON C.FileID = A.FileID
LEFT JOIN FileSea D ON D.FileID = A.FileID
LEFT JOIN SIPOString F ON F.FileID=A.FileID
LEFT JOIN IDFMain H ON H.FileID=A.FileID
LEFT JOIN Customs I ON I.FileID=A.FileID
LEFT JOIN VATRelief V ON V.FileID=A.FileID
LEFT JOIN PortAirPortOperation K ON K.FileID=A.FileID
LEFT JOIN Invoice L ON L.FileID=A.FileID and L.Incoterm=''CIF''' +#WhereStr)
END
The quickest implementation here would be to not use a GROUP BY. I would instead use a SubQuery within your SELECT to perform the SUM of the invoices.
Remove the LEFT JOIN to Invoice and then relace the L.Amount line in the SELECT with a SubQuery as follows
(SELECT SUM(Amount) FROM Invoice WHERE Invoice.FileID = A.FileID and Invoice.Incoterm = 'CIF') [Invoice Value]
If you wish to use a GROUP BY to perform the SUM then you either need to GROUP on all your other columns you SELECT, or perform the GROUP by within a VIEW (probably nested).