Why do these sum operations not "add up" as they should? - sql

Note: This is a follow[on,up] to this question and this question and this question.
The responses all moved me forward, but even that last one, although it improved matters, did not completely solve this issue.
This query:
select monthlysales, MemberNo from ReportingMonthlySales
where unit = 'Abuelos' and CYear = 2017 and cmonth = 3
...returns a bunch of rows, where the Monthly Sales total is $364,121.69
However, when I try to compartmentalize these monthly sales into four categories, although the sum of them all should be the same, the sum is actually astronomically "huger" - the following code returns the vastly inflated value of 23,924,211.30
24 millions of dollars is almost 70 times as much as the 364 thousand that is the actual sum total. Why is this "crazy" inflation occurring?
Here is the fancy pants but apparently bamboozled code:
declare #Unit varchar(30);
declare #Year int = 2017;
declare #Month int = 3;
declare #paramdate datetime;
set #paramdate = convert(datetime,convert(char(4),#Year)
+right('0'+convert(varchar(2),#month),2)
+'01')
IF OBJECT_ID('tempdb.dbo.#Units', 'U') IS NOT NULL
DROP TABLE #Units
select distinct unit
into #Units
from ReportingMonthlySales;
select
u.Unit
, New = sum(case when ccl.Subcategory = 'New' then rms.MonthlySales else 0 end)
, Assumed = sum(case when ccl.Subcategory = 'Assumed' then rms.MonthlySales else 0 end)
, Existing = sum(case when ccl.Subcategory = 'Existing' then rms.MonthlySales else 0 end)
, Organic = sum(case when ccl.Subcategory = 'Organic' then rms.MonthlySales else 0 end)
from #Units u
left join CustomerCategoryLog ccl
on u.Unit = ccl.Unit
and #paramdate >= ccl.begindate and
(#paramdate <= ccl.enddate OR ccl.enddate is null)
left join ReportingMonthlySales rms
on u.Unit = rms.Unit
and rms.cyear = #year
and rms.cmonth = #month
group by u.unit;
The two tables queried are:
CustomerCategoryLog
-------------------
MemberNo (VarChar)
Unit (VarChar)
Custno (VarChar)
Category (VarChar)
Subcategory (VarChar)
BeginDate (DateTime)
EndDate (DateTime)
ChangedBy (VarChar)
ChangedOn (DateTime)
ReportingMonthlySales
---------------------
AutoID (Int)
Unit (VarChar)
MemberNo (VarChar)
NumUnits (Int)
MonthlySales (Money)
CYear (Int)
Cmonth (Int)
CreateDate (DateTime)
Is there something faulty in the fancy-pants sql, or ... ?!?

I suspect the left joins and Or ccl.enddate is null generated a 1 to many
Perhaps a straight inner join will correct the inflation
select
u.Unit
, New = sum(case when ccl.Subcategory = 'New' then rms.MonthlySales else 0 end)
, Assumed = sum(case when ccl.Subcategory = 'Assumed' then rms.MonthlySales else 0 end)
, Existing = sum(case when ccl.Subcategory = 'Existing' then rms.MonthlySales else 0 end)
, Organic = sum(case when ccl.Subcategory = 'Organic' then rms.MonthlySales else 0 end)
from #Units u
join CustomerCategoryLog ccl on u.Unit = ccl.Unit and #paramdate >= ccl.begindate and #paramdate <= ccl.enddate
join ReportingMonthlySales rms on u.Unit = rms.Unit and rms.cyear = #year and rms.cmonth = #month
group by u.unit;

You are doing a join between the RMS table and these other tables. Your code assumes it will find one record for each record in the RMS table. This is not true. This is the cause of getting multiple rows reported and summed. I would think it is most likely that for a particular unit and #paramdate, there is multiple CCL entries.

i think this is causing the duplication
select distinct unit
into #Units
from ReportingMonthlySales;
you basically inserted the same data from the table and used at the left join..
try this updated script
SELECT
rms.Unit,
New = SUM(CASE
WHEN ccl.Subcategory = 'New' THEN rms.MonthlySales
ELSE 0
END),
Assumed = SUM(CASE
WHEN ccl.Subcategory = 'Assumed' THEN rms.MonthlySales
ELSE 0
END),
Existing = SUM(CASE
WHEN ccl.Subcategory = 'Existing' THEN rms.MonthlySales
ELSE 0
END),
Organic = SUM(CASE
WHEN ccl.Subcategory = 'Organic' THEN rms.MonthlySales
ELSE 0
END)
FROM ReportingMonthlySales rms
inner JOIN CustomerCategoryLog ccl
ON rms.Unit = ccl.Unit
where
AND #paramdate >= ccl.begindate
AND (#paramdate <= isnull(ccl.enddate,getdate())
)
AND
rms.cyear = #year
AND rms.cmonth = #month
GROUP BY rms.unit;

Your CustomerCategoryTable as what its name implies could have multiple records for different CustNo for the same UnitNo and that makes your first left join returns duplicate rows which will multiplies the monthly sales, and what I think is that there is no solution for your query except if you try to fix the schema itself for one simple information is that you are trying to find the monthly sales for each unit for it's different subcategorues and your ReportingMonthlySales table doesn't have any information regarding the subcategories.

Related

SQL Server. dynamic query error while using aggregate function

I am little bit new to SQL. I am trying to run below shown dynamic query
SET #SQL ='
select Distinct count(*) TotalCount,
sum(case when ap.FormStatus = ''open'' then 1 else 0 end) AS Totalopenstatus,
sum(case when ap.FormStatus = ''Pending'' then 1 else 0 end) AS TotalPendingstatus,
sum(case when ap.FormStatus = ''Awaiting L1 Review'' then 1 else 0 end) AS TotalAssociates,
sum(case when ap.FormStatus = ''Awaiting L2 Review'' then 1 else 0 end) AS TotalL1reviews,
sum(case when ap.FormStatus = ''Awaiting Delivery Head'' then 1 else 0 end) AS TotalL2reviews
from [dbo].[Appraisals] ap
LEFT join [dbo].[FinalReviewClosures] fi ON ap.FinalReviewClosure_Id = fi.id
join [dbo].[employees] emp ON fi.Employee_Id = emp.id
where fi.FinancialYear ='+#FinancialYear +' AND ap.Quarter = '+#Quarter+' '
but I get this error:
Msg 245, Level 16, State 1, Procedure sp_GetReviewStatus, Line 51 [Batch Start Line 11]
Conversion failed when converting the nvarchar value
Code:
select Distinct count(*) TotalCount,
sum(case when ap.FormStatus = 'open' then 1 else 0 end) AS Totalopenstatus,
sum(case when ap.FormStatus = 'Pending' then 1 else 0 end) AS TotalPendingstatus,
sum(case when ap.FormStatus = 'Awaiting L1 Review' then 1 else 0 end) AS TotalAssociates,
sum(case when ap.FormStatus = 'Awaiting L2 Review' then 1 else 0 end) AS TotalL1reviews,
sum(case when ap.FormStatus = 'Awaiting Delivery Head' then 1 else 0 end) AS TotalL2reviews
from [dbo].[Appraisals] ap
LEFT join [dbo].[FinalReviewClosures] fi ON ap.FinalReviewClosure_Id = fi.id
join [dbo].[employees] emp ON fi.Employee_Id = emp.id
where fi.FinancialYear =2020-2021 AND ap.Quarter = Q3 AND emp.office = ' to data type int.
Please help me fix this problem.
The reason what you have is failing is as has been mentioned. You are injecting values instead of parametrising and these values are creating invalid syntax in your "dynamic" query. (Read on to see why I say "dynamic".)
fi.FinancialYear ='+#FinancialYear +' becomes fi.FinancialYear =2020-2021, which is effectively fi.FinancialYear = -1 (what year is -1?). This will cause an error if fi.FinancialYear isn't able to be converted implicitly to an int.
ap.Quarter = '+#Quarter becomes ap.Quarter = Q3 and unless you have a column called Q3 then you're going to get an invalid column error.
If you are using dynamic SQL then never inject unsanitised values; quote your object names using QUOTENAME and parametrise your parameters (which you can do with sys.sp_executesql).
What you have, however, has no need to be a "dynamic" query; there is nothing dynamic about it. Just use a non-dynamic parametrised query and the query will work fine:
SELECT --DISTINCT --Not needed, as the query will only return 1 row.
--Even if you did have a GROUP BY the DISTINCT isn't needed,
--as the GROUP BY will already put the data in DISTINCT sets.
COUNT(*) AS TotalCount,
SUM(CASE WHEN ap.FormStatus = 'open' THEN 1 ELSE 0 END) AS Totalopenstatus,
SUM(CASE WHEN ap.FormStatus = 'Pending' THEN 1 ELSE 0 END) AS TotalPendingstatus,
SUM(CASE WHEN ap.FormStatus = 'Awaiting L1 Review' THEN 1 ELSE 0 END) AS TotalAssociates,
SUM(CASE WHEN ap.FormStatus = 'Awaiting L2 Review' THEN 1 ELSE 0 END) AS TotalL1reviews,
SUM(CASE WHEN ap.FormStatus = 'Awaiting Delivery Head' THEN 1 ELSE 0 END) AS TotalL2reviews
FROM [dbo].[Appraisals] ap
LEFT JOIN [dbo].[FinalReviewClosures] fi ON ap.FinalReviewClosure_Id = fi.id
JOIN [dbo].[employees] emp ON fi.Employee_Id = emp.id
WHERE fi.FinancialYear = #FinancialYear --I assume fi.FinancialYear and #FinancialYear have the same data type?
AND ap.Quarter = #Quarter; --I assume ap.Quarter and #Quarter have the same data type?
Where clause should be
where fi.FinancialYear ='2020-2021' AND ap.Quarter = 'Q3' AND emp.office = ' to data type int.'
instead of
where fi.FinancialYear =2020-2021 AND ap.Quarter = Q3 AND emp.office = ' to data type int.
Please also let me know the data type of #financialYear and #Quarter

Dynamicaly Naming Columns - Using SQL server 2008

I have query that that references a dynamic calander table, it updates aged periods based on the current date. I am using this table in another query, it sum's sales value based on aged QTR's. These values will update as time passes and I can assign colmn names such as 'AGED1Q' but I would like to find a way to use the actual period name from the calander table. Any sugestions will be greatly appreciated.
Current query is below, I have added a few comment lines where I would like to make the changes. Thanks again
SELECT dbo.CUSTOMER_ORDER.CUSTOMER_ID AS CUST_ID,
SUM(CASE WHEN dbo.UCC_CALENDAR_TODAY_BASED_AGING.QTRs_AGED = -4 THEN dbo.CUST_ORDER_LINE.TOTAL_AMT_ORDERED ELSE 0 END) AS '-4', --As MAX(dbo.UCC_CALENDAR_TODAY_BASED_AGING.QTR) WHERE dbo.UCC_CALENDAR_TODAY_BASED_AGING.QTRs_AGED = -4
SUM(CASE WHEN dbo.UCC_CALENDAR_TODAY_BASED_AGING.QTRs_AGED = -3 THEN dbo.CUST_ORDER_LINE.TOTAL_AMT_ORDERED ELSE 0 END) AS '-3', --As MAX(dbo.UCC_CALENDAR_TODAY_BASED_AGING.QTR) WHERE dbo.UCC_CALENDAR_TODAY_BASED_AGING.QTRs_AGED = -3
SUM(CASE WHEN dbo.UCC_CALENDAR_TODAY_BASED_AGING.QTRs_AGED = -2 THEN dbo.CUST_ORDER_LINE.TOTAL_AMT_ORDERED ELSE 0 END) AS '-2', --As MAX(dbo.UCC_CALENDAR_TODAY_BASED_AGING.QTR) WHERE dbo.UCC_CALENDAR_TODAY_BASED_AGING.QTRs_AGED = -2
SUM(CASE WHEN dbo.UCC_CALENDAR_TODAY_BASED_AGING.QTRs_AGED = -1 THEN dbo.CUST_ORDER_LINE.TOTAL_AMT_ORDERED ELSE 0 END) AS '-1', --As MAX(dbo.UCC_CALENDAR_TODAY_BASED_AGING.QTR) WHERE dbo.UCC_CALENDAR_TODAY_BASED_AGING.QTRs_AGED = -1
SUM(CASE WHEN dbo.UCC_CALENDAR_TODAY_BASED_AGING.QTRs_AGED IN(-4, -3, -2, -1) THEN dbo.CUST_ORDER_LINE.TOTAL_AMT_ORDERED ELSE 0 END) AS 'TOTAL'
FROM dbo.CUSTOMER_ORDER LEFT OUTER JOIN
dbo.UFC_Calander LEFT OUTER JOIN
dbo.UCC_CALENDAR_TODAY_BASED_AGING ON dbo.UFC_Calander.DAY = dbo.UCC_CALENDAR_TODAY_BASED_AGING.DATES ON
dbo.CUSTOMER_ORDER.ORDER_DATE = dbo.UFC_Calander.DAY LEFT OUTER JOIN
dbo.CUSTOMER ON dbo.CUSTOMER_ORDER.CUSTOMER_ID = dbo.CUSTOMER.ID RIGHT OUTER JOIN
dbo.PART RIGHT OUTER JOIN
dbo.CUST_ORDER_LINE ON dbo.PART.ID = dbo.CUST_ORDER_LINE.PART_ID ON dbo.CUSTOMER_ORDER.ID = dbo.CUST_ORDER_LINE.CUST_ORDER_ID
WHERE (dbo.CUSTOMER_ORDER.STATUS <> 'x') AND dbo.UCC_CALENDAR_TODAY_BASED_AGING.QTRs_AGED IN(-4, -3, -2, -1)
GROUP BY dbo.CUSTOMER_ORDER.CUSTOMER_ID
HAVING (dbo.CUSTOMER_ORDER.CUSTOMER_ID <> 'UNFOCO') AND (dbo.CUSTOMER_ORDER.CUSTOMER_ID <> 'QUOTE')
ORDER BY TOTAL DESC

How to remove rows that are all zeros from SQL query

Should be simple to do this but cannot make it work. Have also looked at other similar answers. This code generates a report. There are 3 primary categories: General Adjustments, Finance Charges, and Bad Debts. What I am trying to accomplish...
If these 3 columns are all zeros in a row, delete that row. That's it.
DECLARE #startdate DATETIME
DECLARE #lastdate DATETIME
SET #startdate = '20170701'
SET #lastdate = '20170731'
CREATE TABLE #a
(
ClientName VARCHAR(50),
JobName VARCHAR(50),
JobPartner VARCHAR(40),
[Date] DATETIME,
GenAdj MONEY,
FC MONEY,
BadDebt MONEY,
nomid INT
)
SELECT
C.searchname AS 'CLIENT NAME',
n.date AS 'DATE',
SUM(CASE WHEN NOMTYPEID=3 AND NOMSUBTYPEID=2 THEN TOTAL else 0 END) AS 'GENERAL ADJUSTMENTS',
SUM(CASE WHEN NOMTYPEID=3 AND NOMSUBTYPEID=1 THEN TOTAL else 0 END) AS 'FINANCE CHARGES',
SUM(CASE WHEN NOMTYPEID=3 AND NOMSUBTYPEID=0 THEN TOTAL else 0 END) AS 'BAD DEBTS',
sl.serviceline AS 'DEPARTMENT',
p.name AS 'PARTNER NAME'
FROM
tblNominal N
JOIN
tblNominalAccs A ON N.ContNominalID = A.NominalID
JOIN
tblclient C on N.clientid = C.clientid
LEFT JOIN
tbljob j ON n.jobid = j.JobID
LEFT JOIN
tblpartner p ON j.PartnerID = p.PartnerID
LEFT JOIN
tbljobtype jt ON j.jobtypeid = jt.jobtypeid
LEFT JOIN
tblserviceline sl ON j.servicelineid = sl.servicelineid
WHERE
Date >= #startdate AND DATE <= #LASTDATE
GROUP BY
C.searchname, n.date, sl.serviceline, p.name
ORDER BY
'CLIENT NAME' asc, 'FINANCE CHARGES' asc
DROP TABLE #a
I think I may be overthinking this. How can I delete the rows with all zeros?
Thank you for reading.
You need to use a HAVING clause after your GROUP BY but before your ORDER BY:
HAVING SUM(CASE WHEN NOMTYPEID=3 AND NOMSUBTYPEID=2 THEN TOTAL else 0 END) > 0
OR SUM(CASE WHEN NOMTYPEID=3 AND NOMSUBTYPEID=1 THEN TOTAL else 0 END) > 0
OR SUM(CASE WHEN NOMTYPEID=3 AND NOMSUBTYPEID=0 THEN TOTAL else 0 END) > 0
HAVING is kind of like a WHERE for group results.

Speed up glacial sql statement?

I am writing a report that performs a join on three tables.
PartitionCode has about 127 rows.
AcctListLocal has about 17,000 rows.
TrialBal has, ahem, 70,000,000+ rows
The DBMS is Sybase 15
This is taking forever to execute - over 45 mins. It is a development server used by other teams, but still I don't think it's execution time will be acceptable.
All tables have composite PKs -
AcctListLocal (PK and Index)
=============
acct_local
lv1
lv2
entity_code
PartitonCode (PK and Index)
============
entity_code
partition_code
TrialBal (PK + 3 indexes)
========
**PK/Index 1**
ac_cp
ac_gl
ac_gl_ctrl
ac_taps
code
ccy
id
company
co_ta
cc
entity_code
partition_code
pl_date
pro_num
src
**Index 2**
pl_date
entity_code
pro_num
**Index 3**
pl_date
entity_code
company
ac_gl
**Index 4**
pnl_date
entity_code
partition_code
Is part of my problem I'm joining on incomplete indexes - that is, all the indexes are 'composite' fields, but I'm only matching on a couple of them? do i create indexes on
Trial balance consisting on entity_code and partition_code to match to PartitonCode
and
AccListLocal on entity_code and ac_gl to match the lookup to RegalTrialBal
Or are the CASE statements just horrendous?
SQL is below:
INSERT INTO #VolumesAndValues
SELECT
ahl.lv1 AS base,
ahl.lv2 AS ap,
ahl.lv3 AS mc1,
sum(tb.us) as total,
SUM(CASE WHEN pc.partition_lv2 = 'MA' THEN tb.us ELSE 0 END) AS base,
SUM(CASE WHEN pc.partition_lv2 = 'AJ' THEN tb.us ELSE 0 END) AS batch,
SUM(CASE WHEN pc.partition_lv2 in('ADCG','ADIG') AND 1=1 THEN rtb.us ELSE 0 END) AS net,
SUM(CASE WHEN pc.partition_lv2 = 'FR' THEN tb.us ELSE 0 END) AS fr,
SUM(CASE WHEN pc.partition_lv2 = 'PA' THEN tb.us ELSE 0 END) AS pa,
SUM(CASE WHEN pc.partition_lv2 = 'RE' THEN tb.us ELSE 0 END) AS re,
SUM(CASE WHEN pc.partition_lv2 = 'OF' THEN tb.us ELSE 0 END) AS of,
SUM(CASE WHEN pc.partition_lv2 = 'PR' THEN tb.us ELSE 0 END) AS pr,
'1 Table Data' as rowType
FROM TrialBal tb
LEFT OUTER JOIN AcctListLocal al ON tb.entity_code = al.entity_code
and tb.ac_gl_c = al.ac_local
LEFT OUTER JOIN PartitionCode pc ON pc.partition_code = tb.partition_code
GROUP BY al.lv1, al.lv2, al.lv3
If the data structure allows it, perform your aggregation BEFORE all of your case statements, for example:
INSERT INTO #VolumesAndValues
SELECT
base
,ap
,mc1
,plv2
,sum(subtotal) as total
,SUM(CASE WHEN plv2 = 'MA' THEN subtotal ELSE 0 END) AS base
,SUM(CASE WHEN plv2 = 'AJ' THEN subtotal ELSE 0 END) AS batch
,SUM(CASE WHEN plv2 in('ADCG','ADIG') AND 1=1 THEN othersubtotal ELSE 0 END) AS net
,SUM(CASE WHEN plv2 = 'FR' THEN subtotal ELSE 0 END) AS fr
,SUM(CASE WHEN plv2 = 'PA' THEN subtotal ELSE 0 END) AS pa
,SUM(CASE WHEN plv2 = 'RE' THEN subtotal ELSE 0 END) AS re
,SUM(CASE WHEN plv2 = 'OF' THEN subtotal ELSE 0 END) AS of
,SUM(CASE WHEN plv2 = 'PR' THEN subtotal ELSE 0 END) AS pr
,'1 Table Data' as rowType
FROM (
SELECT
ahl.lv1 AS base
,ahl.lv2 AS ap
,ahl.lv3 AS mc1
,pc.partition_lv2 as plv2
,sum(tb.us) as subtotal
,sum(rtb.us) as othersubtotal
FROM TrialBal tb
LEFT OUTER JOIN AcctListLocal al ON tb.entity_code = al.entity_code
and tb.ac_gl_c = al.ac_local
LEFT OUTER JOIN PartitionCode pc ON pc.partition_code = tb.partition_code
GROUP BY
al.lv1
,al.lv2
,al.lv3
,pc.partition_lv2
) subq
GROUP BY
base
,ap
,mc1
,plv2

How do I use this SQL Stored Procedure to create an INSERT statement?

A workmate has given me this stored procedure and asked for help to create an sql INSERT statement based on its results, but am a little confused to some of the methods. For example, I've never seen a CASE statement in sql. I looked it up but the useage is different from what I was given.
Here is the stored procedure
if #ScheduleType Is Null
SELECT Lu_Schedule_Types.ScheduleType,
SUM(CASE WHEN InductionProduction = 1 THEN CASE WHEN (LEFT(DATENAME(Month,
3)) = 'JAN' THEN ItemQty END END) AS I01,
SUM(CASE WHEN InductionProduction = 1 THEN CASE WHEN (LEFT(DATENAME(Month,
Item_Schedule.ItemScheduleDate), 3))
= 'FEB' THEN ItemQty END END) AS I02,
SUM(CASE WHEN InductionProduction = 2 THEN ItemQty ELSE 0 END) AS PRD,
LmpProjectInfo.PlannedQty,
LmpProjectInfo.AuthorizedQty,
LmpProjectInfo.WbsElementID
FROM Item_Schedule
INNER JOIN Lu_Schedule_Types
ON Item_Schedule.ItemScheduleType = Lu_Schedule_Types.ScheduleTypeId
RIGHT OUTER JOIN LmpProjectInfo
ON Item_Schedule.ItemWbsElement = LmpProjectInfo.WbsElementID
WHERE
(Item_Schedule.IsActive = 1)
AND (Item_Schedule.ItemWbsElement = #WbsElement)
AND (Item_Schedule.ItemScheduleDate < DATEADD(d, 1, #EndDate)) AND
(Item_Schedule.ItemScheduleDate >= #StartDate)
GROUP BY Lu_Schedule_Types.ScheduleType
, Lu_Schedule_Types.ScheduleTypeId
, LmpProjectInfo.PlannedQty
, LmpProjectInfo.AuthorizedQty
, LmpProjectInfo.WbsElementID
ORDER BY Lu_Schedule_Types.ScheduleTypeId
I am supposed to be helping him out but I'm by far a database wizard, and am a little out of my depth here. I'd really appreciate the help/advice/direction.
Thanks much!
This is quick sample that might work for you. This assumes that the table you want to insert data into takes all of the values return from the SELECT statement and that they are of the same type.
As a side note, the reason you might have got a bit confused about the CASE statements is possibly due to the fact there are two main ways to use them in SQL. CASE WHEN... like you have here and CASE #value# WHEN #result# THEN.... A little more searching on the web will lead you to some nice examples. For example this one.
INSERT INTO TABLE_NAME
(
ScheduleType,
I01,
I02,
PRD,
PlannedQty,
AuthorizedQty,
WbsElementID
)
SELECT
Lu_Schedule_Types.ScheduleType,
SUM(CASE WHEN InductionProduction = 1 THEN CASE WHEN (LEFT(DATENAME(Month,
3)) = 'JAN' THEN ItemQty END END) AS I01,
SUM(CASE WHEN InductionProduction = 1 THEN CASE WHEN (LEFT(DATENAME(Month, Item_Schedule.ItemScheduleDate), 3))
= 'FEB' THEN ItemQty END END) AS I02,
SUM(CASE WHEN InductionProduction = 2 THEN ItemQty ELSE 0 END) AS PRD,
LmpProjectInfo.PlannedQty,
LmpProjectInfo.AuthorizedQty,
LmpProjectInfo.WbsElementID
FROM
Item_Schedule INNER JOIN
Lu_Schedule_Types ON Item_Schedule.ItemScheduleType = Lu_Schedule_Types.ScheduleTypeId RIGHT OUTER JOIN
LmpProjectInfo ON Item_Schedule.ItemWbsElement = LmpProjectInfo.WbsElementID
WHERE
(Item_Schedule.IsActive = 1) AND (Item_Schedule.ItemWbsElement = #WbsElement) AND
(Item_Schedule.ItemScheduleDate < DATEADD(d, 1, #EndDate)) AND
(Item_Schedule.ItemScheduleDate >= #StartDate)
GROUP BY Lu_Schedule_Types.ScheduleType, Lu_Schedule_Types.ScheduleTypeId,
LmpProjectInfo.PlannedQty, LmpProjectInfo.AuthorizedQty,
LmpProjectInfo.WbsElementID
ORDER BY Lu_Schedule_Types.ScheduleTypeId
Try this one -
INSERT INTO dbo.table1 -- insert in table
(
ScheduleType
, I01
, I02
, PRD
, PlannedQty
, AuthorizedQty
, WbsElementID
)
SELECT
t.ScheduleType
, I01 = SUM(CASE WHEN InductionProduction = 1 AND MONTH(s.ItemScheduleDate) = 1 THEN ItemQty END)
, I02 = SUM(CASE WHEN InductionProduction = 1 AND MONTH(s.ItemScheduleDate) = 2 THEN ItemQty END)
, PRD = SUM(CASE WHEN InductionProduction = 2 THEN ItemQty END)
, i.PlannedQty
, i.AuthorizedQty
, i.WbsElementID
--INTO #temp_table -- or insert in temp table
FROM dbo.Item_Schedule s
JOIN dbo.Lu_Schedule_Types t ON s.ItemScheduleType = t.ScheduleTypeId
RIGHT JOIN dbo.LmpProjectInfo i ON s.ItemWbsElement = i.WbsElementID
WHERE s.IsActive = 1
AND s.ItemWbsElement = #WbsElement
AND s.ItemScheduleDate < DATEADD(d, 1, #EndDate))
AND s.ItemScheduleDate >= #StartDate
GROUP BY
t.ScheduleType
, t.ScheduleTypeId
, i.PlannedQty
, i.AuthorizedQty
, i.WbsElementID
ORDER BY t.ScheduleTypeId