SQL71005: The reference to the column [106] could not be resolved - sql

This is more annoying then an actual issue, from initially 100's of errors and warning in a visual studio solution the last Rebuild I was left with just 2 identical warnings, and yes they can be suppressed but wondered if anyone else has had a similar issue, appears to be the UNPIVOT and use of an OPENQUERY, and I say all other issues resolved. The Solution builds fine I just prefer no warnings and good housekeeping.
SQL71005: The reference to the column [106] could not be resolved.
SQL71005: The reference to the column [107] could not be resolved.
SELECT #providerCode AS [Provider_Code]
, #siteCode AS [Site_Code]
, #departmentCode AS [Department_Code]
, #startDate8am AS [Period_DateTime_Start]
, #endDate8am AS [Period_DateTime_End]
, [pvt].[items] AS [Metric_ID]
, CAST([pvt].[Value] AS VARCHAR(255)) AS [Metric_Value]
FROM (
SELECT SUM(CASE
WHEN DATEDIFF([mi], [openq1].[ArrivalDateTime], [openq1].[CompletedDateTime]) > 240
THEN 1
ELSE 0
END) AS [106]
,SUM(CASE
WHEN DATEDIFF([mi], [openq1].[ArrivalDateTime], [openq1].[CompletedDateTime]) > 240
THEN 0
ELSE 1
END) AS [107]
FROM OPENQUERY([HRI-INFOPROD],'SELECT [Patient].[PatientId]
, [AdmissionEvent].[AdmitDateTime]
, [AEAttendance].[ArrivalDateTime]
, [AEAttendance].[CompletedDateTime]
FROM [dbo].[Patient]
INNER JOIN [dbo].[AEAttendance]
ON [AEAttendance].[PatientId] = [Patient].[PatientId]
INNER JOIN [dbo].[AdmissionEvent]
ON [Patient].[PatientId] = [AdmissionEvent].[PatientId]
LEFT JOIN [dummy].[ActivePatient] AS [dummy]
ON [Patient].[PatientId] = [dummy].[PatientId]
AND DATEDIFF(HH,[AEAttendance].[CompletedDateTime], [AdmissionEvent].[AdmitDateTime]) BETWEEN -24 AND 24
WHERE [AdmissionEvent].[ADMTYCode] = ''21''
AND [AdmissionEvent].[IsCancelled] = 0
AND [dummy].[PatientId] IS NULL') AS [openq1]
WHERE [openq1].[AdmitDateTime] >= #startDate8am
AND [openq1].[AdmitDateTime] < #endDate8am
AND DATEDIFF([mi], [openq1].[CompletedDateTime], [openq1].[AdmitDateTime]) = (
SELECT MIN(DATEDIFF([mi], [openq2].[CompletedDateTime], [openq2].[AdmitDateTime]))
FROM OPENQUERY([HRI-INFOPROD],'SELECT [AdmissionEvent].[PatientId]
, [AEAttendance].[CompletedDateTime]
, [AdmissionEvent].[AdmitDateTime]
FROM [dbo].[AdmissionEvent]
INNER JOIN [dbo].[AEAttendance]
ON [AEAttendance].[PatientId] = [AdmissionEvent].[PatientId]
WHERE DATEDIFF([HH],[AEAttendance].[CompletedDateTime], [AdmissionEvent].[AdmitDateTime]) BETWEEN -24 AND 24
AND [AdmissionEvent].[ADMTYCode] = ''21''
AND [AdmissionEvent].[IsCancelled] = 0') AS [openq2]
WHERE [openq2].[PatientId] = [openq1].[PatientId]
AND [openq2].[AdmitDateTime] >= #startDate8am
AND [openq2].[AdmitDateTime] < #endDate8am
)
) AS [EDAdmissions]
UNPIVOT ([Value] FOR [items] IN ([106], [107])) AS [pvt];

Related

Oracle stored procedure with function ORA-08103

I have a stored procedure that has a function call, and I get the below errors after about 10 mins of it running:
[Error] Execution (1: 1):
ORA-08103: object no longer exists
ORA-06512: at "CRYSTAL_REPORTS.FT_PAYCOM_ASOF", line 141
ORA-06512: at "CRYSTAL_REPORTS.PROC_DASHQS_PRODUCTION", line 26
ORA-06512: at line 2
However the function does exist and works as expected. Stripping down the query returns results, so I am concerned that complexity may be the cause. I appreciate any help, below is the procedure:
select
to_char(dt.dt,'YYYYMM') yearmonth,
ud.user_id,
CRYSTAL_REPORTS.FT_PAYCOM_ASOF(ud.user_eecode, dt.dt, 'DEPT') department,
CRYSTAL_REPORTS.FT_PAYCOM_ASOF(ud.user_eecode, dt.dt, 'PDEPT') par_department,
sum(case when clm.event_desc = 'NEW-OPEN' then 1 else 0 end) new_claim,
sum(case when clm.event_desc in ('INITIAL-CLOSE', 'RECLOSE', 'VOID') then 1 else 0 end) close_claim,
sum(case when clm.event_desc ='REOPEN' then 1 else 0 end) reopen_claim,
sum(case when clm.event_desc ='TRANSFER-IN' then 1 else 0 end) trans_in_claim,
sum(case when clm.event_desc ='TRANSFER-OUT' then 1 else 0 end) trans_out_claim,
sum(case when res.event_desc ='NEW-OPEN' then 1 else 0 end) new_res,
sum(case when res.event_desc in ('INITIAL-CLOSE','RECLOSE','VOID') then 1 else 0 end) close_res,
sum(case when res.event_desc ='REOPEN' then 1 else 0 end) reopen_res,
sum(case when res.event_desc ='TRANSFER-IN' then 1 else 0 end) trans_in_res,
sum(case when res.event_desc ='TRANSFER-OUT' then 1 else 0 end) trans_out_res,
sum(clm_wh.pending) pending_claims,
sum(res_wh.pending) pending_reserves
from
(select "DATE" dt from CRYSTAL_REPORTS.MV_CALENDAR_MONTHDATE) dt
cross join
crystal_reports.user_director ud
left join
CRYSTAL_REPORTS.MV_PROD_CLM_EVENT clm on clm.USER_ID = ud.USER_ID and to_char(clm.event_date,'YYYYMM') = to_char(dt.dt,'YYYYMM')
left join
CRYSTAL_REPORTS.MV_PROD_RES_EVENT res on res.USER_ID = ud.USER_ID and to_char(res.event_date,'YYYYMM')=to_char(dt.dt,'YYYYMM')
left join
crystal_reports.TBL_CLAIM_PROD_WH clm_wh on clm_wh.ADJUSTER=ud.user_id and clm_wh.type='MONTH' and to_char(dt.dt,'YYYYMM')= clm_wh.datadate
left join
crystal_reports.TBL_FEAT_PROD_WH res_wh on res_wh.ADJUSTER=ud.user_id and res_wh.type='MONTH' and to_char(dt.dt,'YYYYMM')= res_wh.datadate
where
to_char(dt.dt,'YYYYMMDD') = 20210901
and ud.user_id not like '%TEST%'
group by
to_char(dt.dt,'YYYYMM'), ud.user_id,
CRYSTAL_REPORTS.FT_PAYCOM_ASOF(ud.user_eecode, dt.dt, 'DEPT'),
CRYSTAL_REPORTS.FT_PAYCOM_ASOF(ud.user_eecode, dt.dt, 'PDEPT')
The function goes through several IF statements, and ends up using:
SELECT upper(case when uc_dept.detaildesc is null and orig_dept.detaildesc is null then upper(pext_dept.detaildesc) else upper(nvl(uc_dept.detaildesc,orig_dept.detaildesc)) end)
INTO xout_val
FROM crystal_reports.API_PAYCOM_USER_EXTENDED pext
left join crystal_reports.API_PAYCOM_USER_CHANGES uc on pext.EECODE = uc.EECODE and changedesc='PAF: Department Change' and (to_date(substr(changetime, 1,10), 'yyyy-mm-dd')) <= asof
left join crystal_reports.api_paycom_category pext_dept on pext_dept.detailcode=pext.DEPARTMENT_CODE
left join crystal_reports.api_paycom_category uc_dept on uc_dept.DETAILCODE=uc.new_value
left join (select eecode, orig_value,rn
from
(
select eecode,old_value orig_value, row_number() over (partition by eecode order by (to_date(substr(changetime, 1,10), 'yyyy-mm-dd')) asc) rn
from
crystal_reports.API_PAYCOM_USER_CHANGES orig_val
where changedesc='PAF: Department Change'
)
) orig_val on pext.eecode=orig_val.eecode and orig_val.rn=1
left join crystal_reports.api_paycom_category orig_dept on orig_dept.detailcode=orig_val.orig_value
where
acct=pext.eecode
order by (to_date(substr(changetime, 1,10), 'yyyy-mm-dd')) desc
FETCH NEXT 1 ROWS ONLY
It is very hard to remote diagnose such an error but in my experience the most likely cause of this error is another process/user that has removed the object since the operation has begun.
Alternatively there are also some Oracle bugs related to this error and you might want to check your alert log and eventually ask Oracle for help using MOS.

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

Select "case when"... yields grouped results... how to obtain aggregate data?

Newer SQL user working with SQL Server 2014 SP2.
I'm trying to determine how to improve my results on a particular query.
The problem is that when I select data with a Case When, it requires me to use group by to aggregate the data.
I am trying to eliminate this group by, and have not been able to determine a viable method for this query.
Query yields these results:
StoreID Devices playing devices FullScreenPlays PIPPlays
--------------------------------------------------------
1296 1 0 0 0
1296 7 7 7 0
1296 7 7 0 7
I am trying to achieve something more like this:
StoreID Devices playing devices FullScreenPlays PIPPlays
--------------------------------------------------------------
1296 8 7 7 7
I've tried several variants of calling the group by, and I've tried several variants of the case when, but I can't seem to figure out what I'm doing wrong...
Any insight would be appreciated!
SQL code is here:
DECLARE #Location varchar(50) = '1296'
SELECT
Location.ExternalCode As [StoreID],
COUNT(DISTINCT imdd.DeviceID) AS Devices,
COUNT(DISTINCT esr.DeviceID) AS [playing devices],
(CASE
WHEN (esr.EventID = 925)
THEN (COUNT(DISTINCT esr.DeviceID))
ELSE 0
END) AS [FullScreenPlays],
(CASE
WHEN (esr.EventID = 926)
THEN (COUNT(DISTINCT esr.DeviceID))
ELSE 0
END) AS [PIPPlays]
FROM
[iSenseMD].dbo.Location WITH (NOLOCK)
INNER JOIN
iSenseMD.dbo.LocationAttribute la WITH (NOLOCK) ON Location.LocationID = la.LocationID
AND la.AttributeID = 7
AND la.Value = 1
LEFT JOIN
[iSenseMD].[dbo].Device imdd WITH (NOLOCK) ON location.LocationID = imdd.LocationID
AND imdd.DeviceName NOT IN ('iX Gateway', 'A312778', 'A294874', '334873')
LEFT JOIN
[iSenseAnalytics].[dbo].[EventStringRollup] esr WITH (NOLOCK) ON imdd.LocationID = esr.LocationID
AND imdd.DeviceID = esr.DeviceID
AND esr.IntervalID = 1
AND esr.EventID IN (925, 926) --all plays
AND esr.RollupTimestamp >= dateadd(day, datediff(day, 1, GETDATE()), 0)
AND esr.RollupTimestamp < dateadd(day, datediff(day, 0, GETDATE()), 0)
WHERE
Location.IsActive = 1
AND Location.LocationName NOT LIKE '%duplicate%'
AND Location.ExternalCode = #Location --this to add the declaration above as site constraint
GROUP BY
Location.ExternalCode, esr.EventID
ORDER BY
iSenseMD.dbo.Location.ExternalCode
Any insight would be appreciated!
Thanks!
I would put the query in a CTE and then aggregate it from there
WITH CTE_Example
AS
( use iSenseMD
go
DECLARE #Location varchar(50) = '1296'
SELECT Location.ExternalCode As [StoreID]
,count(distinct imdd.DeviceID) as Devices
,count(distinct esr.DeviceID) as [playing devices]
,(case when (esr.EventID = 925) Then (count (distinct esr.DeviceID)) Else 0 End) As [FullScreenPlays]
,(case when (esr.EventID = 926) Then (count (distinct esr.DeviceID)) Else 0 End) As [PIPPlays]
FROM [iSenseMD].dbo.Location WITH (NOLOCK)
INNER JOIN iSenseMD.dbo.LocationAttribute la WITH (NOLOCK)
ON Location.LocationID = la.LocationID
AND la.AttributeID = 7
AND la.Value = 1
left JOIN [iSenseMD].[dbo].Device imdd WITH (NOLOCK) ON location.LocationID = imdd.LocationID
AND imdd.DeviceName NOT IN ('iX Gateway','A312778','A294874','334873')
left JOIN [iSenseAnalytics].[dbo].[EventStringRollup] esr WITH (NOLOCK) ON imdd.LocationID = esr.LocationID and imdd.DeviceID = esr.DeviceID
AND esr.IntervalID = 1
AND esr.EventID IN (925, 926) --all plays
AND esr.RollupTimestamp >= dateadd(day,datediff(day,1,GETDATE()),0)
AND esr.RollupTimestamp < dateadd(day,datediff(day,0,GETDATE()),0)
WHERE Location.IsActive = 1
AND Location.LocationName NOT LIKE '%duplicate%'
AND Location.ExternalCode = #Location --this to add the declaration above as site constraint
GROUP BY Location.ExternalCode
,esr.EventID)
--A GROUP BY might not be allowed either, I can't remember. But I think it'll be fine, let me know if there are any issues
/* ORDER BY
iSenseMD.dbo.Location.ExternalCode */
--I don't think an ORDER BY is allowed in a CTE so I have it commented out for now. Is it an absolute within the query?
SELECT StoreID, SUM(Devices), SUM([playing devices]), SUM(FullScreenPlays),
SUM(PIPPlays)
FROM CTE_Example
GROUP BY StoreID
Hope this helps and please let me know if there are any errors!
You need to place your case statement inside your count aggregate. This way you can remove the EventID in the group by
Example:
COUNT(DISTINCT
CASE WHEN (esr.EventID = 925) THEN esr.DeviceID
ELSE NULL
END) AS [FullScreenPlays]
Original:
(CASE
WHEN (esr.EventID = 925)
THEN (COUNT(DISTINCT esr.DeviceID))
ELSE 0
END) AS [FullScreenPlays]

Can't get PIVOT to work

I am trying to use PIVOT for the first time and I am not able to get it to work, I just can't seem to figure out what I am doing wrong.
I started with a nasty select statement. When I get these results I can get results and what I have been doing is exporting to Excel and using the pivot functions in there. When I get the data into Excel, I do this as my operations: http://imgur.com/N024rEi
So I then went to the next step and tried to do the whole pivot in SQL but can't get it to work. Here is my code:
SELECT DISTINCT #tmp1.AuthID
, #tmp1.ProviderID
, #tmp1.ProviderName
, #tmp1.LOCID
, #tmp1.LOCDesc
, '$' + CONVERT(VARCHAR,CAST(#tmp1.TotAuthAmt AS MONEY),-1) AS 'ToAuthAmt'
, CONVERT(VARCHAR(10), #tmp1.AuthDate, 101) AS AuthDate,
CONVERT(VARCHAR(10), #tmp1.AuthExpirationDate, 101) AS AuthExpirationDate
, DATEDIFF(D,#tmp1.AuthDate,#tmp1.AuthExpirationDate) AS AuthLenInDays
, (CASE WHEN
ISNULL(#tmp2.TotPaidAmt, 0) = 0 THEN '$0.00'
ELSE '$' + CONVERT(VARCHAR,CAST(#tmp2.TotPaidAmt AS MONEY),-1)
END) AS TotPaidAmt,
#tmp1.NbrOfAuthorizations
, #tmp1.UnitsAuthorized
, #tmp1.RatePerUnit
, #tmp1.CAREMODE
, (CASE WHEN
ISNULL(#tmp2.UnitsAdjudicated, 0) = 0 THEN 0
ELSE #tmp2.UnitsAdjudicated
END) AS AuthUnitsClaimed
, (#tmp1.UnitsAuthorized -
(CASE WHEN
ISNULL(#tmp2.UnitsAdjudicated, 0) = 0 THEN 0
ELSE #tmp2.UnitsAdjudicated
END)) AS UnclaimedAuths
, (CASE WHEN
ISNULL(#tmp2.ExpiredAuths, 0) = 0 THEN 0
ELSE 1
END) AS ExpiredIndicator
FROM (SELECT
DISTINCT #tmp1.AuthID
, #tmp1.ProviderID
, #tmp1.ProviderName
, #tmp1.LOCID
, #tmp1.LOCDesc
, '$' + CONVERT(VARCHAR,CAST(#tmp1.TotAuthAmt AS MONEY),-1) AS 'ToAuthAmt'
, CONVERT(VARCHAR(10), #tmp1.AuthDate, 101) AS AuthDate
, CONVERT(VARCHAR(10), #tmp1.AuthExpirationDate, 101) AS AuthExpirationDate
, DATEDIFF(D,#tmp1.AuthDate,#tmp1.AuthExpirationDate) AS AuthLenInDays
, (CASE WHEN
ISNULL(#tmp2.TotPaidAmt, 0) = 0 THEN '$0.00'
ELSE '$' + CONVERT(VARCHAR,CAST(#tmp2.TotPaidAmt AS MONEY),-1)
END) AS TotPaidAmt,
#tmp1.UnitsAuthorized
, #tmp1.RatePerUnit
, #tmp1.CAREMODE
, (CASE WHEN
ISNULL(#tmp2.UnitsAdjudicated, 0) = 0 THEN 0
ELSE #tmp2.UnitsAdjudicated
END) AS AuthUnitsClaimed
, (#tmp1.UnitsAuthorized -
(CASE WHEN
ISNULL(#tmp2.UnitsAdjudicated, 0) = 0 THEN 0
ELSE #tmp2.UnitsAdjudicated
END)) AS UnclaimedAuths
, (CASE WHEN
ISNULL(#tmp2.ExpiredAuths, 0) = 0 THEN 0
ELSE 1
END) AS ExpiredIndicator
FROM #tmp1
LEFT JOIN #tmp2
ON #tmp2.AuthID = #tmp1.AuthID
GROUP BY #tmp1.AuthID, #tmp1.ProviderID, #tmp1.LOCID, #tmp1.LOCDesc, #tmp1.UnitsAuthorized, #tmp1.RatePerUnit, #tmp1.FamilyID, #tmp1.ProviderName, #tmp1.TotAuthAmt,
#tmp1.AuthDate, #tmp1.AuthExpirationDate, #tmp2.TotPaidAmt, #tmp1.NbrOfAuthorizations, #tmp1.CAREMODE, #tmp2.UnitsAdjudicated, #tmp2.ExpiredAuths
)#tmp1
PIVOT (
SUM(#tmp1.NbrOfAuthorizations) FOR ProviderName
IN (#tmp1.ProviderName)
) AS #tmp1
What do I need to change here to get this to work? Also, how would I add the other items as shown in the screen shot?
EDIT1: Looks like I was able to get results after using this for my PIVOT:
PIVOT
(SUM(NbrOfAuthorizations) FOR [ProviderName] IN (element1, element2, etc.)
) PivotResults1
PIVOT
(AVG(AuthLenInDays) FOR [CAREMODE] IN ([element1])
) PivotResults2
but still having a couple of issues...the SUM statement doesn't actually seem to SUM the values for a specific value into one column. I see a '1' or NULL for each cell, as in this example: http://www.codeproject.com/Tips/500811/Simple-Way-To-Use-Pivot-In-SQL-Query . The other thing is for my AVG column, I can't figure out how to change the name of that column, it is always the name of element1.
i think instead of
IN (#tmp1.ProviderName)
you need
IN ([element1],[element2],[element3], ... )
with element*n* being all variations of content of #tmp1.ProviderName. In the SELECT part at the very top you must then list these elements as columns
and
you should give different aliases to the two table statements, you have #tmp1 twice in there.
Try an easy test example of PIVOT with much less columns first. If You figure it out it is very powerful. I love the pivot features in excel (pivotcharts!) but the database can do aggregation so much faster.

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