Related
I want to replace the 1st and 2nd parameter in DATEADD function depending on the result of cteTable. Is this something possible? Do I need to create a parameter? Thank you in advance. Happy new year!
;with cteDP as(
SELECT CODE, MEASSUREMENT, DEFEXPIRYDATEDAYS,
CASE WHEN MEASSUREMENT = 0 THEN 'DAY'
WHEN MEASSUREMENT = 1 THEN 'WEEK'
WHEN MEASSUREMENT = 2 THEN 'MONTH'
WHEN MEASSUREMENT = 3 THEN 'YEARS'
ELSE 'SECOND'
END AS MEASUREMENTINWORD
FROM PW001C06 C06 WHERE CODE IN ('ADC','MMC')
)
select * from cteDP
UPDATE P05
SET P05.EXPIRYDATE = CASE
WHEN P05.CODE = 'ADC' THEN DATEADD('cteDocProperties.MEASUREMENTINWORD', #2nd parameter, EXPIRYDATE)
-- WHEN P05.CODE = 'MMC' THEN DATEADD(YEAR, 4, EXPIRYDATE)
-- WHEN P05.CODE = 'LD00' THEN DATEADD(YEAR, 3, EXPIRYDATE)
ELSE EXPIRYDATE
END
FROM PW001P05 P05
INNER JOIN cteDP
ON cteDP.CODE = P05.CODE
WHERE P05.PIN = 1
AND P05.CODE IN ('ADC','MMC')
You can directly JOIN to the table expression:
UPDATE P05
SET
P05.EXPIRYDATE = CASE
WHEN P05.CODE = 'ADC' THEN
CASE WHEN MEASUREMENTINWORD = 'SECOND'
THEN DATEADD(SECOND, MEASSUREMENT, EXPIRYDATE)
CASE WHEN MEASUREMENTINWORD = 'DAY'
THEN DATEADD(DAY, MEASSUREMENT, EXPIRYDATE)
CASE WHEN MEASUREMENTINWORD = 'MONTH'
THEN DATEADD(MONTH, MEASSUREMENT, EXPIRYDATE)
CASE WHEN MEASUREMENTINWORD = 'YEAR'
THEN DATEADD(YEAR, MEASSUREMENT, EXPIRYDATE)
ELSE EXPIRYDATE
END
FROM PW001P05 P05
INNER JOIN
(
SELECT
CODE
, MEASSUREMENT
, DEFEXPIRYDATEDAYS
, CASE
WHEN MEASSUREMENT = 0 THEN 'DAY'
WHEN MEASSUREMENT = 1 THEN 'WEEK'
WHEN MEASSUREMENT = 2 THEN 'MONTH'
WHEN MEASSUREMENT = 3 THEN 'YEARS'
ELSE 'SECOND'
END AS MEASUREMENTINWORD
FROM PW001C06 C06 WHERE CODE IN ('ADC','MMC')
) cteDP
ON cteDP.CODE = P05.CODE
WHERE P05.PIN = 1
AND P05.CODE IN ('ADC','MMC')
I have taken over the support of an Excel 2010 macro and need to change the sort order of a recordset.
The query below worked before I attempted to change the order by adding rl.list_order.
Now I'm getting the error "The multi-part identifier could not be bound" and have tried many alternatives and have researched on this site for a solution but haven't been able to solve this. Can someone please help.
SELECT ips_rc.project, lfbe.Category, ips_rc.roster_id, ips_rc.role_category, ips_rc.role_title AS Role, ips_rc.role_code, ips_rc.role_title + ' (' + ips_rc.role_code + ')' AS PS_Role, CASE WHEN ISNULL(lfbe.Pronto_Role_Code, '') = '' THEN 'TO_BE_MAPPED' ELSE ISNULL(lfbe.Pronto_Role_Code, '') END AS Pronto_Role_Code, CASE WHEN ISNULL(lfbe.Pronto_Role_Code_Description, '') = '' THEN ips_rc.role_title ELSE ISNULL(lfbe.Pronto_Role_Code_Description, '') END AS Pronto_Role_Code_Description, ISNULL(lfbe.Rate, 0) AS Rate, CASE WHEN ISNULL(lfbe.Pronto_Role_Code_Old, '') = '' THEN ips_rc.role_title ELSE lfbe.Pronto_Role_Code_Old END AS Pronto_Role_Code_Old, CASE WHEN ISNULL(lfbe.Pronto_Role_Code_Description_Old, '') = '' THEN 'TO_BE_MAPPED' ELSE lfbe.Pronto_Role_Code_Description_Old END AS Pronto_Role_Code_Description_Old, ips_rc.Shift, ips_rc.UOM, ips_rc.Date, ips_rc.DHours, ips_rc.NHours FROM (SELECT psrc.project, pr_jcm.customer, pr_jcm.subcode, psrc.roster_id, psrc.role_id, psrc.role_category, psrc.role_title,
psrc.role_code, CASE WHEN SUM(CASE WHEN psrc.Date BETWEEN psrc.start_date AND psrc.end_date THEN psrc.NWorkHours ELSE 0 END) OVER (PARTITION BY psrc.project, psrc.roster_id) >= SUM(CASE WHEN psrc.Date BETWEEN psrc.start_date AND psrc.end_date THEN psrc.DWorkHours ELSE 0 END) OVER (PARTITION BY psrc.project, psrc.roster_id) THEN 'Night Shifts' ELSE 'Day Shifts' END AS Shift, 'HOURS' AS UOM, psrc.Date, psrc.DHours, psrc.NHours FROM (SELECT rcd.project, rcd.start_date, rcd.end_date, rcd.roster_id, rcd.role1_id AS role_id, CASE WHEN rb_test1.role1_id IS NOT NULL THEN rb_test1.category WHEN rb_test2.role1_id IS NOT NULL THEN rb_test2.category WHEN rb_test3.role1_id IS NOT NULL THEN rb_test3.category ELSE rcd.role_category END AS role_category, CASE WHEN rb_test1.role1_id IS NOT NULL THEN rb_test1.title WHEN rb_test2.role1_id IS NOT NULL THEN rb_test2.title WHEN rb_test3.role1_id IS NOT NULL THEN rb_test3.title ELSE rcd.role_title END AS role_title, CASE WHEN rb_test1.role1_id IS NOT NULL THEN CAST(rb_test1.band_r
ole_id AS VARCHAR) WHEN rb_test2.role1_id IS NOT NULL THEN CAST(rb_test2.band_role_id AS VARCHAR) WHEN rb_test3.role1_id IS NOT NULL THEN CAST(rb_test3.band_role_id AS VARCHAR) ELSE rcd.role_code END AS role_code, rcd.shift_date AS Date, SUM(CASE WHEN rcd.shift_ampm = 'day' THEN rcd.shift_time ELSE 0 END) AS DHours, SUM(CASE WHEN rcd.shift_ampm = 'day' AND rcd.shift_type = 'work' THEN rcd.shift_time ELSE 0 END) AS DWorkHours, SUM(CASE WHEN rcd.shift_ampm = 'day' AND rcd.shift_type = 'eqmob' THEN rcd.shift_time ELSE 0 END) AS DEqmobHours, SUM(CASE WHEN rcd.shift_ampm = 'day' AND rcd.shift_type = 'eqdemob' THEN rcd.shift_time ELSE 0 END) AS DEqdemobHours, SUM(CASE WHEN rcd.shift_ampm = 'night' THEN rcd.shift_time ELSE 0 END) AS NHours, SUM(CASE WHEN rcd.shift_ampm = 'night' AND rcd.shift_type = 'work' THEN rcd.shift_time ELSE 0 END) AS NWorkHours, SUM(CASE WHEN rcd.shift_ampm = 'night' AND rcd.shift_type = 'eqmob' THEN rcd.shift_time ELSE 0 END) AS NEqmobHours, SUM(CASE WHEN rcd.shift_ampm = 'night' AND rcd.sh
ift_type = 'eqdemob' THEN rcd.shift_time ELSE 0 END) AS NEqdemobHours FROM OPENQUERY([LFMANAGE], 'SELECT p.job_no AS project, p.start_date, p.end_date, rs.roster_id, IFNULL(rs.role_id, 0) AS role1_id, IFNULL(r.role2_id, 0) AS role2_id, IFNULL(r.role3_id, 0) AS role3_id, rl.category AS role_category, rl.title AS role_title, rl.role_code AS role_code, rs.shift_date, rs.shift_ampm, rs.shift_time, rs.shift_type, s.client_id FROM lfmanage.t_roster_shift rs JOIN lfmanage.t_project AS p ON p.project_id = rs.project_id LEFT JOIN lfmanage.t_site AS s ON s.site_id = p.site_id JOIN lfmanage.t_roster AS r ON r.roster_id = rs.roster_id JOIN lfmanage.t_role AS rl ON rl.role_id = rs.role_id WHERE p.job_no = ''700704'' AND CASE WHEN ISNULL(rs.deleted) THEN 0 ELSE rs.deleted END = 0') AS rcd LEFT OUTER JOIN (SELECT client_id, band_role_id, title, CASE WHEN CHARINDEX(UPPER(title),'SUPER') > 0 THEN 'super' ELSE 'trade' END AS category, role1_id, role2_id, role3_id FROM OPENQUERY([LFMANAGE], 'SELECT br.client_id, MIN(brs.band_r
ole_id) AS band_role_id, br.title, brs.role1_id, brs.role2_id, brs.role3_id FROM t_band_role_set AS brs INNER JOIN t_band_role AS br ON br.band_role_id = brs.band_role_id WHERE IFNULL(brs.role1_id, 0) <> 0 AND IFNULL(brs.role2_id, 0) <> 0 AND IFNULL(brs.role3_id, 0) <> 0 GROUP BY br.client_id, br.title, brs.role1_id, brs.role2_id, brs.role3_id')) AS rb_test1 ON rb_test1.client_id = rcd.client_id AND rb_test1.role1_id = rcd.role1_id AND rb_test1.role2_id = rcd.role2_id AND rb_test1.role3_id = rcd.role3_id LEFT OUTER JOIN (SELECT client_id, band_role_id, title, CASE WHEN CHARINDEX(UPPER(title),'SUPER') > 0 THEN 'super' ELSE 'trade' END AS category, role1_id, role2_id FROM OPENQUERY([LFMANAGE], 'SELECT br.client_id, MIN(brs.band_role_id) AS band_role_id, br.title, brs.role1_id, brs.role2_id FROM t_band_role_set AS brs INNER JOIN t_band_role AS br ON br.band_role_id = brs.band_role_id WHERE IFNULL(brs.role1_id, 0) <> 0 AND IFNULL(brs.role2_id, 0) <> 0 GROUP BY br.client_id, br.title, brs.role1_id, brs.role2_id '
)) AS rb_test2 ON rb_test2.client_id = rcd.client_id AND rb_test2.role1_id = rcd.role1_id AND rb_test2.role2_id = rcd.role2_id LEFT OUTER JOIN (SELECT client_id, band_role_id, title, CASE WHEN CHARINDEX(UPPER(title),'SUPER') > 0 THEN 'super' ELSE 'trade' END AS category, role1_id, role3_id FROM OPENQUERY([LFMANAGE], 'SELECT br.client_id, MIN(brs.band_role_id) AS band_role_id, br.title, brs.role1_id, brs.role3_id FROM t_band_role_set AS brs INNER JOIN t_band_role AS br ON br.band_role_id = brs.band_role_id WHERE IFNULL(brs.role1_id, 0) <> 0 AND IFNULL(brs.role3_id, 0) <> 0 GROUP BY br.client_id, br.title, brs.role1_id, brs.role3_id ')) AS rb_test3 ON rb_test3.client_id = rcd.client_id AND rb_test3.role1_id = rcd.role1_id AND rb_test3.role3_id = rcd.role3_id WHERE rcd.shift_date > '2017-01-01' GROUP BY rcd.project, rcd.start_date, rcd.end_date, rcd.roster_id, rcd.role1_id, CASE WHEN rb_test1.role1_id IS NOT NULL THEN rb_test1.category WHEN rb_test2.role1_id IS NOT NULL THEN rb_test2.category WHEN rb_test3.role
1_id IS NOT NULL THEN rb_test3.category ELSE rcd.role_category END, CASE WHEN rb_test1.role1_id IS NOT NULL THEN rb_test1.title WHEN rb_test2.role1_id IS NOT NULL THEN rb_test2.title WHEN rb_test3.role1_id IS NOT NULL THEN rb_test3.title ELSE rcd.role_title END, CASE WHEN rb_test1.role1_id IS NOT NULL THEN CAST(rb_test1.band_role_id AS VARCHAR) WHEN rb_test2.role1_id IS NOT NULL THEN CAST(rb_test2.band_role_id AS VARCHAR) WHEN rb_test3.role1_id IS NOT NULL THEN CAST(rb_test3.band_role_id AS VARCHAR) ELSE rcd.role_code END, rcd.shift_date) AS psrc INNER JOIN (SELECT job_no AS project, Client AS customer, '3700002213' AS subcode FROM [dbo].[vw_PlanningSystem_Projects] WHERE job_no = '700704') AS pr_jcm ON pr_jcm.project = psrc.project) AS ips_rc LEFT OUTER JOIN (SELECT rates.Client, rates.SubCode, mapping.Category, mapping.Shift, mapping.IPS_Role_Code, rates.Pronto_Role_Code, rates.Pronto_Role_Code_Description, rates.Rate, rates.Pronto_Role_Code_Old, rates.Pronto_Role_Code_Description_Old FROM (SELECT UPPER(Ca
tegory) AS Category, 'Day Shifts' AS Shift, IPS_Role_Code, Day_Cost_Code As Pronto_Role_Code FROM [LFBudgetEstimate].[dbo].[LFBE_RoleCode_MasterMapping] UNION ALL SELECT UPPER(Category) AS Category, 'Night Shifts' AS Shift, IPS_Role_Code, Night_Cost_Code As Pronto_Role_Code FROM [LFBudgetEstimate].[dbo].[LFBE_RoleCode_MasterMapping]) AS mapping INNER JOIN (SELECT Client, SubCode, CASE WHEN Shift = 'Day Shift' THEN 'Day Shifts' WHEN Shift = 'Night Shift' THEN 'Night Shifts' Else '' END AS Shift, Pronto_Role_Code, Pronto_Role_Code_Description, Rate, Pronto_Role_Code_Old, Pronto_Role_Code_Description_Old FROM [LFBudgetEstimate].[dbo].[LFBE_SubCodes_Rates]) AS rates ON rates.Shift = mapping.Shift AND rates.Pronto_Role_Code = mapping.Pronto_Role_Code) AS lfbe ON lfbe.Client = ips_rc.customer AND lfbe.SubCode = ips_rc.subCode AND lfbe.Shift = ips_rc.Shift AND lfbe.IPS_Role_Code = ips_rc.role_code ORDER BY ips_rc.project ASC, ips_rc.role_title ASC, rl.list_order
Thanks for your help
Even with the formatting, you've got a lot going on here... Stack Overflow veterans, I'm just starting to dip my toes in here, so if this isn't correct, give me some grace.
In your first OPENQUERY statement, I don't see rl.list_order as a field being returned. If that's a column you're trying to ORDER BY, I think you should be able to add rl.list_order to your SELECT list within that statement which you alias as rcd.
Since that's within a nested sub-query, you'll want to elevate it to each of the calling queries. I think it's something like this... Try it out and post back with any errors.
SELECT ips_rc.ListOrder
, ips_rc.project
, lfbe.Category
, ips_rc.roster_id
, ips_rc.role_category
, ips_rc.role_title AS [ROLE]
, ips_rc.role_code
, ips_rc.role_title + ' (' + ips_rc.role_code + ')' AS PS_Role
, CASE
WHEN ISNULL(lfbe.Pronto_Role_Code, '') = ''
THEN 'TO_BE_MAPPED'
ELSE ISNULL(lfbe.Pronto_Role_Code, '')
END AS Pronto_Role_Code
, CASE
WHEN ISNULL(lfbe.Pronto_Role_Code_Description, '') = ''
THEN ips_rc.role_title
ELSE ISNULL(lfbe.Pronto_Role_Code_Description, '')
END AS Pronto_Role_Code_Description
, ISNULL(lfbe.Rate, 0) AS Rate
, CASE
WHEN ISNULL(lfbe.Pronto_Role_Code_Old, '') = ''
THEN ips_rc.role_title
ELSE lfbe.Pronto_Role_Code_Old
END AS Pronto_Role_Code_Old
, CASE
WHEN ISNULL(lfbe.Pronto_Role_Code_Description_Old, '') = ''
THEN 'TO_BE_MAPPED'
ELSE lfbe.Pronto_Role_Code_Description_Old
END AS Pronto_Role_Code_Description_Old
, ips_rc.Shift
, ips_rc.UOM
, ips_rc.DATE
, ips_rc.DHours
, ips_rc.NHours
FROM (
SELECT psrc.ListOrder -- Added
, psrc.project
, pr_jcm.customer
, pr_jcm.subcode
, psrc.roster_id
, psrc.role_id
, psrc.role_category
, psrc.role_title
, psrc.role_code
, CASE
WHEN SUM(CASE
WHEN psrc.DATE BETWEEN psrc.start_date
AND psrc.end_date
THEN psrc.NWorkHours
ELSE 0
END) OVER (PARTITION BY psrc.project, psrc.roster_id) >= SUM(CASE
WHEN psrc.DATE BETWEEN psrc.start_date
AND psrc.end_date
THEN psrc.DWorkHours
ELSE 0
END) OVER (PARTITION BY psrc.project, psrc.roster_id)
THEN 'Night Shifts'
ELSE 'Day Shifts'
END AS Shift, 'HOURS' AS UOM, psrc.DATE, psrc.DHours, psrc.NHours
FROM (
SELECT rcd.list_order --Added
, rcd.project
, rcd.start_date
, rcd.end_date
, rcd.roster_id
, rcd.role1_id AS role_id
, CASE
WHEN rb_test1.role1_id IS NOT NULL
THEN rb_test1.category
WHEN rb_test2.role1_id IS NOT NULL
THEN rb_test2.category
WHEN rb_test3.role1_id IS NOT NULL
THEN rb_test3.category
ELSE rcd.role_category
END AS role_category
, CASE
WHEN rb_test1.role1_id IS NOT NULL
THEN rb_test1.title
WHEN rb_test2.role1_id IS NOT NULL
THEN rb_test2.title
WHEN rb_test3.role1_id IS NOT NULL
THEN rb_test3.title
ELSE rcd.role_title
END AS role_title
, CASE
WHEN rb_test1.role1_id IS NOT NULL
THEN CAST(rb_test1.band_role_id AS VARCHAR)
WHEN rb_test2.role1_id IS NOT NULL
THEN CAST(rb_test2.band_role_id AS VARCHAR)
WHEN rb_test3.role1_id IS NOT NULL
THEN CAST(rb_test3.band_role_id AS VARCHAR)
ELSE rcd.role_code
END AS role_code, rcd.shift_date AS DATE
, SUM(CASE
WHEN rcd.shift_ampm = 'day'
THEN rcd.shift_time
ELSE 0
END) AS DHours
, SUM(CASE
WHEN rcd.shift_ampm = 'day'
AND rcd.shift_type = 'work'
THEN rcd.shift_time
ELSE 0
END) AS DWorkHours
, SUM(CASE
WHEN rcd.shift_ampm = 'day'
AND rcd.shift_type = 'eqmob'
THEN rcd.shift_time
ELSE 0
END) AS DEqmobHours
, SUM(CASE
WHEN rcd.shift_ampm = 'day'
AND rcd.shift_type = 'eqdemob'
THEN rcd.shift_time
ELSE 0
END) AS DEqdemobHours
, SUM(CASE
WHEN rcd.shift_ampm = 'night'
THEN rcd.shift_time
ELSE 0
END) AS NHours
, SUM(CASE
WHEN rcd.shift_ampm = 'night'
AND rcd.shift_type = 'work'
THEN rcd.shift_time
ELSE 0
END) AS NWorkHours
, SUM(CASE
WHEN rcd.shift_ampm = 'night'
AND rcd.shift_type = 'eqmob'
THEN rcd.shift_time
ELSE 0
END) AS NEqmobHours
, SUM(CASE
WHEN rcd.shift_ampm = 'night'
AND rcd.shift_type = 'eqdemob'
THEN rcd.shift_time
ELSE 0
END) AS NEqdemobHours
FROM OPENQUERY([LFMANAGE], 'SELECT p.job_no AS project, p.start_date, p.end_date, rs.roster_id, IFNULL(rs.role_id, 0) AS role1_id, IFNULL(r.role2_id, 0) AS role2_id, IFNULL(r.role3_id, 0) AS role3_id, rl,ListOrder, rl.category AS role_category, rl.title AS role_title, rl.role_code AS role_code, rs.shift_date, rs.shift_ampm, rs.shift_time, rs.shift_type, s.client_id FROM lfmanage.t_roster_shift rs JOIN lfmanage.t_project AS p ON p.project_id = rs.project_id LEFT JOIN lfmanage.t_site AS s ON s.site_id = p.site_id JOIN lfmanage.t_roster AS r ON r.roster_id = rs.roster_id JOIN lfmanage.t_role AS rl ON rl.role_id = rs.role_id WHERE p.job_no = ''700704'' AND CASE WHEN ISNULL(rs.deleted) THEN 0 ELSE rs.deleted END = 0') AS rcd --Added
LEFT JOIN (
SELECT client_id
, band_role_id
, title
, CASE
WHEN CHARINDEX(UPPER(title), 'SUPER') > 0
THEN 'super'
ELSE 'trade'
END AS category
, role1_id
, role2_id
, role3_id
FROM OPENQUERY([LFMANAGE], 'SELECT br.client_id, MIN(brs.band_role_id) AS band_role_id, br.title, brs.role1_id, brs.role2_id, brs.role3_id FROM t_band_role_set AS brs INNER JOIN t_band_role AS br ON br.band_role_id = brs.band_role_id WHERE IFNULL(brs.role1_id, 0) <> 0 AND IFNULL(brs.role2_id, 0) <> 0 AND IFNULL(brs.role3_id, 0) <> 0 GROUP BY br.client_id, br.title, brs.role1_id, brs.role2_id, brs.role3_id')
) AS rb_test1
ON rb_test1.client_id = rcd.client_id
AND rb_test1.role1_id = rcd.role1_id
AND rb_test1.role2_id = rcd.role2_id
AND rb_test1.role3_id = rcd.role3_id
LEFT JOIN (
SELECT client_id, band_role_id, title, CASE
WHEN CHARINDEX(UPPER(title), 'SUPER') > 0
THEN 'super'
ELSE 'trade'
END AS category, role1_id, role2_id
FROM OPENQUERY([LFMANAGE], 'SELECT br.client_id, MIN(brs.band_role_id) AS band_role_id, br.title, brs.role1_id, brs.role2_id FROM t_band_role_set AS brs INNER JOIN t_band_role AS br ON br.band_role_id = brs.band_role_id WHERE IFNULL(brs.role1_id, 0) <> 0 AND IFNULL(brs.role2_id, 0) <> 0 GROUP BY br.client_id, br.title, brs.role1_id, brs.role2_id ')
) AS rb_test2
ON rb_test2.client_id = rcd.client_id
AND rb_test2.role1_id = rcd.role1_id
AND rb_test2.role2_id = rcd.role2_id
LEFT JOIN (
SELECT client_id, band_role_id, title, CASE
WHEN CHARINDEX(UPPER(title), 'SUPER') > 0
THEN 'super'
ELSE 'trade'
END AS category, role1_id, role3_id
FROM OPENQUERY([LFMANAGE], 'SELECT br.client_id, MIN(brs.band_role_id) AS band_role_id, br.title, brs.role1_id, brs.role3_id FROM t_band_role_set AS brs INNER JOIN t_band_role AS br ON br.band_role_id = brs.band_role_id WHERE IFNULL(brs.role1_id, 0) <> 0 AND IFNULL(brs.role3_id, 0) <> 0 GROUP BY br.client_id, br.title, brs.role1_id, brs.role3_id ')
) AS rb_test3
ON rb_test3.client_id = rcd.client_id
AND rb_test3.role1_id = rcd.role1_id
AND rb_test3.role3_id = rcd.role3_id
WHERE rcd.shift_date > '2017-01-01'
GROUP BY rcd.list_order --Added
, rcd.project
, rcd.start_date
, rcd.end_date
, rcd.roster_id
, rcd.role1_id
, CASE
WHEN rb_test1.role1_id IS NOT NULL
THEN rb_test1.category
WHEN rb_test2.role1_id IS NOT NULL
THEN rb_test2.category
WHEN rb_test3.ROLE1_id IS NOT NULL
THEN rb_test3.category
ELSE rcd.role_category
END
, CASE
WHEN rb_test1.role1_id IS NOT NULL
THEN rb_test1.title
WHEN rb_test2.role1_id IS NOT NULL
THEN rb_test2.title
WHEN rb_test3.role1_id IS NOT NULL
THEN rb_test3.title
ELSE rcd.role_title
END
, CASE
WHEN rb_test1.role1_id IS NOT NULL
THEN CAST(rb_test1.band_role_id AS VARCHAR)
WHEN rb_test2.role1_id IS NOT NULL
THEN CAST(rb_test2.band_role_id AS VARCHAR)
WHEN rb_test3.role1_id IS NOT NULL
THEN CAST(rb_test3.band_role_id AS VARCHAR)
ELSE rcd.role_code
END
, rcd.shift_date
) AS psrc
INNER JOIN (
SELECT job_no AS project
, Client AS customer
, '3700002213' AS subcode
FROM [dbo].[vw_PlanningSystem_Projects]
WHERE job_no = '700704'
) AS pr_jcm
ON pr_jcm.project = psrc.project
) AS ips_rc
LEFT JOIN (
SELECT rates.Client
, rates.SubCode
, mapping.Category
, mapping.Shift
, mapping.IPS_Role_Code
, rates.Pronto_Role_Code
, rates.Pronto_Role_Code_Description
, rates.Rate
, rates.Pronto_Role_Code_Old
, rates.Pronto_Role_Code_Description_Old
FROM (
SELECT UPPER(Category) AS Category
, 'Day Shifts' AS Shift
, IPS_Role_Code
, Day_Cost_Code AS Pronto_Role_Code
FROM [LFBudgetEstimate].[dbo].[LFBE_RoleCode_MasterMapping]
UNION ALL
SELECT UPPER(Category) AS Category
, 'Night Shifts' AS Shift
, IPS_Role_Code
, Night_Cost_Code AS Pronto_Role_Code
FROM [LFBudgetEstimate].[dbo].[LFBE_RoleCode_MasterMapping]
) AS mapping
INNER JOIN (
SELECT Client
, SubCode
, CASE
WHEN Shift = 'Day Shift'
THEN 'Day Shifts'
WHEN Shift = 'Night Shift'
THEN 'Night Shifts'
ELSE ''
END AS Shift
, Pronto_Role_Code
, Pronto_Role_Code_Description
, Rate
, Pronto_Role_Code_Old
, Pronto_Role_Code_Description_Old
FROM [LFBudgetEstimate].[dbo].[LFBE_SubCodes_Rates]
) AS rates
ON rates.Shift = mapping.Shift
AND rates.Pronto_Role_Code = mapping.Pronto_Role_Code
) AS lfbe
ON lfbe.Client = ips_rc.customer
AND lfbe.SubCode = ips_rc.subCode
AND lfbe.Shift = ips_rc.Shift
AND lfbe.IPS_Role_Code = ips_rc.role_code
ORDER BY ips_rc.project ASC, ips_rc.role_title ASC, ips_rc.list_order ASC
You're right CSharp821 there's an awful lot going on there. I made the changes you suggested and it now works!
You are trying to access alias rl, however the rl alias is only visible within the OPENQUERY which has an alias of rcd. Try order by rcd.list_order instead of rl.list_order
I am working with a legacy system that only accepts dd/mm/yyyy in the XML for the data fields otherwise it mucks up the data entry.
I have tried every which way to attempt to force my data fields to display as dd/mm/yyyy, I have attempted to CONVERT to DATETIME 103, I have tried declaring it as a VARCHAR and everytime time it returns as 2018-05-11 for example.
How can I force the returned field to display as DD/MM/YYYY, this is a snippet of my code, excuse how messy it is unfortunately it is very linear and the system that accepts the XML is very basic.
SELECT TOP 1 1 'job/queue',
#Branch 'job/branch',
CASE WHEN myli.PolRef# IS NOT NULL THEN 'update-broomsrisk' ELSE 'create-broomsrisk' END 'parameters/yzt/char20.1',
SUBSTRING(#PolicyRef,1,6) 'broomsdata/broomsclient/bcm/refno',
#PolicyRef 'broomsdata/broomspolicy/bpy/refno',
CASE WHEN myli.PolRef# IS NOT NULL THEN myli.key# ELSE NULL END 'broomsdata/broomspolicy/myli/KEY',
(SELECT ISNULL(ct2.convictiondate,ct2.offencedate) FROM #ConvictionTable AS ct2 WHERE ct2.RowNo = 1) 'broomsdata/broomspolicy/myli/Date1',
(SELECT ct2.code FROM #ConvictionTable AS ct2 WHERE ct2.RowNo = 1) 'broomsdata/broomspolicy/myli/Code1',
(SELECT ct2.fine FROM #ConvictionTable AS ct2 WHERE ct2.RowNo = 1) 'broomsdata/broomspolicy/myli/Fine1',
(SELECT ct2.noofpoints FROM #ConvictionTable AS ct2 WHERE ct2.RowNo = 1) 'broomsdata/broomspolicy/myli/Points1',
(SELECT ISNULL(ct2.convictiondate,ct2.offencedate) FROM #ConvictionTable AS ct2 WHERE ct2.RowNo = 2) 'broomsdata/broomspolicy/myli/Date2',
(SELECT ct2.code FROM #ConvictionTable AS ct2 WHERE ct2.RowNo = 2) 'broomsdata/broomspolicy/myli/Code2',
(SELECT ct2.fine FROM #ConvictionTable AS ct2 WHERE ct2.RowNo = 2) 'broomsdata/broomspolicy/myli/Fine2',
(SELECT ct2.noofpoints FROM #ConvictionTable AS ct2 WHERE ct2.RowNo = 2) 'broomsdata/broomspolicy/myli/Points2',
(SELECT ISNULL(ct2.convictiondate,ct2.offencedate) FROM #ConvictionTable AS ct2 WHERE ct2.RowNo = 3) 'broomsdata/broomspolicy/myli/Date3',
(SELECT ct2.code FROM #ConvictionTable AS ct2 WHERE ct2.RowNo = 3) 'broomsdata/broomspolicy/myli/Code3',
(SELECT ct2.fine FROM #ConvictionTable AS ct2 WHERE ct2.RowNo = 3) 'broomsdata/broomspolicy/myli/Fine3',
(SELECT ct2.noofpoints FROM #ConvictionTable AS ct2 WHERE ct2.RowNo = 3) 'broomsdata/broomspolicy/myli/Points3',
(SELECT ISNULL(ct2.convictiondate,ct2.offencedate) FROM #ConvictionTable AS ct2 WHERE ct2.RowNo = 4) 'broomsdata/broomspolicy/myli/Date4',
(SELECT ct2.code FROM #ConvictionTable AS ct2 WHERE ct2.RowNo = 4) 'broomsdata/broomspolicy/myli/Code4',
(SELECT ct2.fine FROM #ConvictionTable AS ct2 WHERE ct2.RowNo = 4) 'broomsdata/broomspolicy/myli/Fine4',
(SELECT ct2.noofpoints FROM #ConvictionTable AS ct2 WHERE ct2.RowNo = 4) 'broomsdata/broomspolicy/myli/Points4'
FROM #ConvictionTable AS ct
LEFT OUTER JOIN [FIG-SQL-SRV].InfoCentre.dbo.ic_BD_MYLI AS myli ON ct.branch = myli.B# AND ct.policyRef = myli.PolRef#
FOR XML PATH('xmlexecute'), TYPE;
The Fields I'm trying to force are the 'Date1'/'Date2' etc. fields.
Cheers
Use CONVERT(varchar(10), YourDateColumn, 103). I think your mistake was trying to convert to a datetime (I'm guessing you tried CONVERT(datetime, YourDateColumn, 103)) while using a style code; date/time datatypes, in SQL Server, have no format. Trying to format them won't do anything.
For example: SELECT CONVERT(varchar(10), GETDATE(), 103); returns the varchar(10) value '11/05/2018'.
Edit: The below is to (temporary) assist the OP in showing how i create XML for OpenInterchange. The OP is using a lot of Sub Selects, something that doesn't help the speed of the query. I've highlighted, a couple of points for the OP to note as well:
SELECT K.Insco AS Insurer,
K.B# AS Branch,
K.PolRef# AS PolicyRef,
K.ClaimRef# AS ClaimRef,
--XML Generation starts here.
(SELECT(SELECT K.B# AS branch,
'OO' AS operator,
'PDF' AS printtype
FOR XML PATH('job'),TYPE),
(SELECT (SELECT 'update-claim' AS [Char20.1]
FOR XML PATH('yzt'),TYPE)
FOR XML PATH('parameters'),TYPE),
(SELECT (SELECT (SELECT K.Ref# AS Refno
FOR XML PATH('bcm'),TYPE)
FOR XML PATH('broomsclient'),TYPE),
(SELECT (SELECT K.PolRef# AS Refno
FOR XML PATH('bpy'),TYPE)
FOR XML PATH('broomspolicy'),TYPE),
(SELECT (SELECT K.ClaimRef# AS [Claim.No],
K.[Claim No] AS [Ins.Claim.Ref],
K.KGMSettled AS [Claim.Settled],
K.KGMReserve AS [Claim.Reserve],
K.KGMReserve + K.KGMSettled As [Claim.Amount],
K.KGMStatus AS [Stat.Desc],
CASE K.KGMStatus WHEN 'Settled' THEN 'SETT'
WHEN 'Ouststanding' THEN 'OUTS'
WHEN 'Declined' THEN 'DECL'
WHEN 'Not Taken up' THEN 'NTUP'
WHEN 'Withdrawn' THEN 'WITH' END AS [stat.code],
CONVERT(varchar(10),K.[Notified Date],103) AS [Date.repd], --First example of the dd/MM/yyyy format
CONVERT(varchar(10),K.[Loss Date],103) AS [Loss.date], --Another example of the dd/MM/yyyy format
CASE WHEN K.[Date Closed] IS NOT NULL THEN CONVERT(varchar(10), GETDATE(), 103) END AS [Stat.date], -- and another example of the dd/MM/yyyy format
CONVERT(varchar(10),K.[Date Closed],103) AS [Date.Settled], --you get the idea. :)
CASE WHEN K.[Date Closed] IS NOT NULL AND K.[Incident Type] = 'Windscreen' THEN 'Yes'
WHEN K.[Date Closed] IS NULL THEN ''
WHEN K.[NCB Decision] = 'Allowed' THEN 'Yes'
WHEN K.[NCB Decision] = 'Disallowed' THEN 'Yes' END AS [Settled.free]
/*
CASE WHEN K.[Date Closed] IS NOT NULL AND K.[Incident Type] = 'Windscreen' THEN 'Yes'
WHEN K.KGMReserve + K.KGMSettled = 0 AND K.[Date Closed] IS NOT NULL THEN 'Yes'
WHEN K.KGMReserve + K.KGMSettled > 0 AND K.[Date Closed] IS NOT NULL THEN 'No'
ELSE '' END AS [Settled.free]*/
FOR XML PATH('bch'),TYPE),
(SELECT K.BCAKey AS [KEY],
K.[Vehicle Reg# No] AS [Reg.no],
K.[Driver Name] AS [Driver],
K.[ AD Paid] AS [Pay.ad],
K.[AD Reserve] AS [Reserve.ad],
K.[TPD Paid] + K.[TPI Paid] AS [Pay.tp],
K.[TPD Reserve] + K.[TPI Reserve] AS [Reserve.tp],
--K.[TPI Paid] AS [Pay.others],
--K.[TPI Reserve] AS [Reserve.others],
0 AS [Pay.others],
0 AS [Reserve.others],
K.KGMSettled AS [Pay.total],
K.KGMReserve AS [Reserve.Total],
K.[Recovery] AS [Pay.recovs],
K.[AD Recovery Reserve] AS [Reserve.recovs],
'Updated by FileDrop Service. XML Generated on ' + CONVERT(varchar(10),GETDATE(),103) as [Remarks4]
FOR XML PATH('bca'),TYPE),
(SELECT CONVERT(varchar(10),GETDATE(),103) AS [date],
LEFT(CONVERT(varchar(10),GETDATE(),108),5) AS [time],
'OO' AS [op],
'FileDrop' AS [Name],
K.KGMSettled AS [Settled],
K.KGMReserve AS [Reserve],
K.KGMSettled + K.KGMReserve As [Total],
--CONVERT(varchar(10),K.DataToDate,103) AS [EffDate],
CASE WHEN K.KGMSettled != K.BCHSettled THEN 'Payment'
WHEN K.KGMReserve != K.BCHReserve THEN 'Reserve Adjustment'
ELSE 'Payment' END AS [Notes]
FOR XML PATH('clam'),TYPE)
FOR XML PATH('broomsclaim'),TYPE)
FOR XML PATH('broomsdata'),TYPE)
FOR XML PATH('xmlexecute'),TYPE) AS InputXML,
GETDATE() AS DateGenerated,
0 AS TestLoad
FROM KGMCGStandard_viw K
WHERE K.ClaimsFound = 1
AND K.KGMFound = 1
AND (K.KGMSettled != K.BCHSettled
OR K.KGMReserve != K.BCHReserve
OR (CONVERT(date,K.KGMClosure) != CONVERT(date,BCHClosure)
OR (K.KGMClosure IS NULL AND K.BCHClosure IS NOT NULL)
OR (K.KGMClosure IS NOT NULL AND K.BCHClosure IS NULL))
OR (CASE WHEN K.[Date Closed] IS NOT NULL AND K.[Incident Type] = 'Windscreen' THEN 'Yes'
WHEN K.[NCB Decision] = 'Allowed' THEN 'Yes'
WHEN K.[NCB Decision] = 'Disallowed' THEN 'No' END != K.Settled_Free
OR (K.[Date Closed] IS NULL AND K.Settled_free IS NULL)))
AND NOT EXISTS (SELECT 1
FROM AutoloadXML_tbl A
WHERE A.Branch = K.B#
AND A.PolicyRef = K.PolRef#
AND A.ClaimRef = K.ClaimRef#
AND (A.DateSubmitted IS NULL
OR A.Installed = 0))
ORDER BY K.ClaimRef# ASC;
Since you already figured out the date part I will leave that up to you but your query could be simplified majorly using conditional aggregation. I used square braces around the column names instead of single quotes. Sure those work but I consider that a bad habit because it is difficult to decide if it is a string literal or a column alias. I also prefer to use alias = but that is more a preference thing. I also prefer leading commas which is also a preference thing.
Pretty sure this query should do the same thing.
SELECT 1 as 'job/queue',
#Branch as 'job/branch',
CASE WHEN myli.PolRef# IS NOT NULL THEN 'update-broomsrisk' ELSE 'create-broomsrisk' END as 'parameters/yzt/char20.1',
SUBSTRING(#PolicyRef,1,6) as 'broomsdata/broomsclient/bcm/refno',
#PolicyRef as 'broomsdata/broomspolicy/bpy/refno',
CASE WHEN myli.PolRef# IS NOT NULL THEN myli.key# ELSE NULL END as 'broomsdata/broomspolicy/myli/KEY'
, [broomsdata/broomspolicy/myli/Date1] = max(case when ct.RowNo = 1 then ISNULL(ct.convictiondate, ct.offencedate) end)
, [broomsdata/broomspolicy/myli/Code1] = max(case when ct.RowNo = 1 then ct.code end)
, [broomsdata/broomspolicy/myli/Fine1] = max(case when ct.RowNo = 1 then ct.fine end)
, [broomsdata/broomspolicy/myli/Points1] = max(case when ct.RowNo = 1 then ct.noofpoints end)
, [broomsdata/broomspolicy/myli/Date2] = max(case when ct.RowNo = 2 then ISNULL(ct.convictiondate, ct.offencedate) end)
, [broomsdata/broomspolicy/myli/Code2] = max(case when ct.RowNo = 2 then ct.code end)
, [broomsdata/broomspolicy/myli/Fine2] = max(case when ct.RowNo = 2 then ct.fine end)
, [broomsdata/broomspolicy/myli/Points] = max(case when ct.RowNo = 2 then ct.noofpoints end)
, [broomsdata/broomspolicy/myli/Date3] = max(case when ct.RowNo = 3 then ISNULL(ct.convictiondate, ct.offencedate) end)
, [broomsdata/broomspolicy/myli/Code3] = max(case when ct.RowNo = 3 then ct.code end)
, [broomsdata/broomspolicy/myli/Fine3] = max(case when ct.RowNo = 3 then ct.fine end)
, [broomsdata/broomspolicy/myli/Points3] = max(case when ct.RowNo = 3 then ct.noofpoints end)
, [broomsdata/broomspolicy/myli/Date4] = max(case when ct.RowNo = 4 then ISNULL(ct.convictiondate, ct.offencedate) end)
, [broomsdata/broomspolicy/myli/Code4] = max(case when ct.RowNo = 4 then ct.code end)
, [broomsdata/broomspolicy/myli/Fine4] = max(case when ct.RowNo = 4 then ct.fine end)
, [broomsdata/broomspolicy/myli/Points4] = max(case when ct.RowNo = 4 then ct.noofpoints end)
FROM #ConvictionTable AS ct
LEFT OUTER JOIN [FIG-SQL-SRV].InfoCentre.dbo.ic_BD_MYLI AS myli ON ct.branch = myli.B# AND ct.policyRef = myli.PolRef#
GROUP BY #Branch
, CASE WHEN myli.PolRef# IS NOT NULL THEN 'update-broomsrisk' ELSE 'create-broomsrisk' END
, SUBSTRING(#PolicyRef,1,6)
, #PolicyRef
, CASE WHEN myli.PolRef# IS NOT NULL THEN myli.key# ELSE NULL END
FOR XML PATH('xmlexecute'), TYPE
I have a pretty complex SQL query that I need run every Monday morning (early).
I've gotten the SQL query to give me the data I need but i'm at a loss how to have the query insert the results into a table.
The declare statements are causing the issue (I THINK)
Does anyone have any ideas? Ideally I'd like to setup a job that just runs and appends to a table.
Thanks.
K.
DECLARE #StartDateTime DATETIME;
DECLARE #EndDateTime DATETIME;
DECLARE #ReportOn CHAR(1);
DECLARE #Group1 VARCHAR(25);
DECLARE #Group2 VARCHAR(25);
DECLARE #Date1Grouping VARCHAR(25);
DECLARE #Date2Grouping VARCHAR(25);
DECLARE #DivisionID VARCHAR(10);
DECLARE #GroupSubsidiaries BIT;
SET #StartDateTime = '3/06/2013' ;
SET #EndDateTime = '3/12/2013' ;
SET #ReportOn = 'S' ;
SET #Group1 = 'Due Date' ;
SET #Group2 = 'Sale Date' ;
SET #Date1Grouping = 'Yearly' ;
SET #Date2Grouping = 'Daily' ;
SET #GroupSubsidiaries = 1 ;
DECLARE #GLEntries TABLE (ID INT PRIMARY KEY, Amount FLOAT, EntryDateTime DATETIME, GLClassificationType INT,
GroupID INT, GLAccountID INT, GLAccountClassTypeID INT, AccountID INT,
TransHeaderID INT, TransDetailID INT, DivisionID INT,
Classification INT, IsTaxable BIT, TaxClassID INT,
GoodsItemID INT, GoodsItemClassTypeID INT);
-- 'C' used for Closed Reports
IF ( #ReportOn = 'C' )
INSERT INTO #GLEntries
SELECT GL.ID, GL.Amount, GL.EntryDateTime, GL.GLClassificationType,
GL.GroupID, GL.GLAccountID, GL.GLAccountClassTypeID, GL.AccountID,
GL.TransactionID, GL.TransDetailID, GL.DivisionID,
GL.Classification, GL.IsTaxable, GL.TaxClassID,
GL.GoodsItemID, GL.GoodsItemClassTypeID
FROM GL WITH(NOLOCK)
WHERE (GL.GLAccountID <> 53)
AND EXISTS( SELECT 1
FROM TransHeader
WHERE ClosedDate BETWEEN #StartDateTime and #EndDateTime
AND ID = GL.TransactionID )
ELSE
INSERT INTO #GLEntries
SELECT GL.ID, GL.Amount, GL.EntryDateTime, GL.GLClassificationType,
GL.GroupID, GL.GLAccountID, GL.GLAccountClassTypeID, GL.AccountID,
GL.TransactionID, GL.TransDetailID, GL.DivisionID,
GL.Classification, GL.IsTaxable, GL.TaxClassID,
GL.GoodsItemID, GL.GoodsItemClassTypeID
FROM GL WITH(NOLOCK)
WHERE (GL.GLAccountID <> 53)
AND GL.EntryDateTime between #StartDateTime and #EndDateTime
;
SELECT Orders.*, Totals.*,
( SELECT -Sum(Amount)
FROM #GLEntries GL1
LEFT JOIN TransHeader TH ON (TH.ID = GL1.TransHeaderID)
WHERE GL1.GLClassificationType = 2005)
as TotalTaxes,
#StartDateTime as theStartDate,
#EndDateTime as theEndDate,
-- Selects Group1 based on #Group1
CASE
WHEN #Group1 = 'Product' THEN Product
WHEN #Group1 = 'None' THEN 'None'
WHEN #Group1 = 'Due Date' THEN
CASE
WHEN #Date1Grouping = 'Daily' THEN Convert( VARCHAR(25), Orders.DueDate, 112)
WHEN #Date1Grouping = 'Weekly' THEN Convert( VARCHAR(25), DateAdd(d, -DatePart(dw,Orders.DueDate) + 1, Orders.DueDate), 112 )
WHEN #Date1Grouping = 'Monthly' THEN Cast( DatePart(yyyy, Orders.DueDate) * 100 + DatePart(mm,Orders.DueDate) AS VARCHAR(7) )
WHEN #Date1Grouping = 'Yearly' THEN Cast( DatePart(yyyy, Orders.DueDate) AS VARCHAR(4) )
END
WHEN #Group1 = 'Sales Date' THEN
CASE
WHEN #Date1Grouping = 'Daily' THEN Convert( VARCHAR(25), Orders.EntryDateTime, 112 )
WHEN #Date1Grouping = 'Weekly' THEN Convert( VARCHAR(25), DateAdd(d, -DatePart(dw,Orders.EntryDateTime) + 1, Orders.EntryDateTime), 112 )
WHEN #Date1Grouping = 'Monthly' THEN Cast( DatePart(yyyy, Orders.EntryDateTime) * 100 + DatePart(mm, Orders.EntryDateTime) AS VARCHAR(7) )
WHEN #Date1Grouping = 'Yearly' THEN Cast( DatePart(yyyy, Orders.EntryDateTime) AS VARCHAR(4) )
END
WHEN #Group1 = 'Primary Salesperson' THEN Salesperson1LastName + Salesperson1FirstName
WHEN #Group1 = 'Customer Origin' THEN OriginName
WHEN #Group1 = 'Industry' THEN IndustryName
WHEN #Group1 = 'Order Origin' THEN OrderOriginName
WHEN #Group1 = 'Postal Code' THEN PostalCode
WHEN #Group1 = 'Postal Code 3 Digit' THEN PostalCode3Digit
WHEN #Group1 = 'Product Category' THEN ProductCategory
WHEN #Group1 = 'Account' THEN AccountName
WHEN #Group1 = 'Company Name' THEN CompanyName
WHEN #Group1 = 'Company Frequency' THEN CompanyName
WHEN #Group1 = 'Company Volume' THEN CompanyName
WHEN #Group1 = 'GL Department' THEN GLDepartment
WHEN #Group1 = 'Industry (Parent)' THEN IndustryParent
WHEN #Group1 = 'Company Origin (Parent)' THEN CompanyOriginParent
WHEN #Group1 = 'Order Origin (Parent)' THEN OrderOriginParent
WHEN #Group1 = 'Region' THEN RegionName
END AS Group1,
CASE
WHEN #Group2 = 'Product' THEN Product
WHEN #Group2 = 'None' THEN 'None'
WHEN #Group2 = 'Due Date' THEN
CASE
WHEN #Date2Grouping = 'Daily' THEN Convert( VARCHAR(25), Orders.DueDate, 112 )
WHEN #Date2Grouping = 'Weekly' THEN Convert( VARCHAR(25), DateAdd(d, -DatePart(dw, Orders.DueDate) + 1, Orders.DueDate), 112 )
WHEN #Date2Grouping = 'Monthly' THEN Cast( DatePart(yyyy, Orders.DueDate) * 100 + DatePart(mm, Orders.DueDate) AS VARCHAR(7) )
WHEN #Date2Grouping = 'Yearly' THEN Cast( DatePart(yyyy, Orders.DueDate) AS VARCHAR(4) )
END
WHEN #Group2 = 'Sales Date' THEN
CASE
WHEN #Date2Grouping = 'Daily' THEN Convert( VARCHAR(25), Orders.EntryDateTime, 112 )
WHEN #Date2Grouping = 'Weekly' THEN Convert( VARCHAR(25), DateAdd(d, -DatePart(dw, Orders.EntryDateTime) + 1, Orders.EntryDateTime), 112 )
WHEN #Date2Grouping = 'Monthly' THEN Cast( DatePart(yyyy, Orders.EntryDateTime) * 100 + DatePart(mm, Orders.EntryDateTime) AS VARCHAR(7) )
WHEN #Date2Grouping = 'Yearly' THEN Cast( DatePart(yyyy, Orders.EntryDateTime) AS VARCHAR(4) )
END
WHEN #Group2 = 'Primary Salesperson' THEN Salesperson1LastName + Salesperson1FirstName
WHEN #Group2 = 'Customer Origin' THEN OriginName
WHEN #Group2 = 'Industry' THEN IndustryName
WHEN #Group2 = 'Order Origin' THEN OrderOriginName
WHEN #Group2 = 'Postal Code' THEN PostalCode
WHEN #Group2 = 'Postal Code 3 Digit' THEN PostalCode3Digit
WHEN #Group2 = 'Product Category' THEN ProductCategory
WHEN #Group2 = 'Account' THEN AccountName
WHEN #Group2 = 'Company' THEN CompanyName
WHEN #Group2 = 'GL Department' THEN GLDepartment
WHEN #Group2 = 'Region' THEN RegionName
END AS Group2
FROM ( SELECT 1 AS StoreID,
fx_Return.DivisionID,
EmployeeGroup.DivisionName,
fx_Return.TransHeaderID,
fx_Return.OrderNumber,
fx_Return.InvoiceNumber,
fx_Return.CompanyName,
-fx_Return.GLAmount AS Amount,
GLAccount.AccountName,
fx_Return.StatusText,
fx_Return.Classification,
fx_Return.GLClassificationType,
fx_Return.Description,
fx_Return.EntryDateTime,
fx_Return.DiscountPrice,
fx_Return.SaleDate,
fx_Return.DueDate,
fx_Return.BuiltDate,
fx_Return.OrderCreatedDate,
fx_Return.ClosedDate,
fx_Return.AccountID,
fx_Return.GLDepartment,
fx_Return.SalesPerson1ID,
SalesPerson1.FirstName AS SalesPerson1FirstName,
SalesPerson1.LastName AS SalesPerson1LastName,
Origin.ItemName AS OriginName,
CASE
WHEN Origin.ParentID = 11 THEN Origin.ItemName
ELSE CompanyOriginParent.ItemName
END AS CompanyOriginParent,
Industry.ItemName AS IndustryName,
CASE
WHEN IndustryParent.ID = 10 THEN Industry.ItemName
ELSE IndustryParent.ItemName
END AS IndustryParent,
fx_Return.OrderOriginName,
CASE
WHEN OrderOrigin.ParentID = 13 THEN OrderOrigin.ItemName
ELSE OrderOriginParent.ItemName
END AS OrderOriginParent,
Address.PostalCode,
SUBSTRING(Address.PostalCode,1,3) AS PostalCode3Digit,
Product.ItemName AS Product,
ProductCategory.ElementName AS ProductCategory,
ProductSubCategory.ElementName AS ProductSubCategory,
Region.ItemName AS RegionName
FROM ( SELECT GL2.EntryDateTime,
SUM( CASE
WHEN #ReportOn NOT IN ('P','B') THEN GL2.Amount
WHEN GL2.GLAccountID IN (11, 12) THEN -GL2.Amount
WHEN GL2.GLClassificationType IN (4000, 2005) THEN GL2.Amount
ELSE 0
END ) AS GLAmount,
GL2.GLAccountID,
CASE
WHEN GL2.GLClassificationType IN (4000,5002)
AND COALESCE(GL2.Classification,-1) NOT IN (100,200,300,400,500) THEN 100
ELSE GL2.Classification
END AS Classification,
GL2.GLClassificationType,
GL2.DivisionID,
GL2.IsTaxable,
GL2.TaxClassID,
GL2.GroupID,
TransHeader.StatusText,
CAST(TransHeader.Description AS VARCHAR(30)) AS Description,
TransHeader.DueDate,
TransHeader.OrderOriginName,
-- TransHeader Related Fields
GL2.TransHeaderID,
TransHeader.OrderNumber,
COALESCE( TransHeader.InvoiceNumber, TransHeader.OrderNumber) as InvoiceNumber,
TransHeader.CreditMemoOrderID,
TransHeader.Salesperson1ID,
TransHeader.OrderOriginID,
TransHeader.InvoiceAddressID as OrderInvoiceAddressID,
TransHeader.PromotionID,
Transheader.DiscountPrice,
TransHeader.PricingLevelID,
TransHeader.ClosedDate,
TransHeader.OrderCreatedDate,
TransHeader.SaleDate,
TransHeader.BuiltDate,
-- TransDetail Related Fields
GL2.TransDetailID,
TransDetail.LineItemNumber,
TransDetail.Quantity,
GL2.GoodsItemID,
GL2.GoodsItemClassTypeID,
TransDetail.GoodsItemCode,
Station.StationName as GLDepartment,
-- Account Related Fields
GL2.AccountID,
ParentAccount.CompanyName,
ParentAccount.AccountNumber,
ParentAccount.PricingPlanTypeID,
ParentAccount.IndustryID,
ParentAccount.RegionID,
ParentAccount.OriginID as CompanyOriginID,
ParentAccount.Marketing3ID,
ParentAccount.BillingAddressID as CompanyBillingAddressID
FROM #GLEntries GL2
LEFT JOIN TransHeader WITH(NOLOCK) ON (TransHeader.ID = GL2.TransHeaderID)
LEFT JOIN Account WITH(NOLOCK) ON (Account.ID = GL2.AccountID)
LEFT JOIN Account ParentAccount WITH(NOLOCK) ON ParentAccount.ID = ( CASE WHEN #GroupSubsidiaries = 1 THEN COALESCE(Account.ParentID, Account.ID) ELSE Account.ID END )
LEFT JOIN TransDetail WITH(NOLOCK) ON (TransDetail.ID = GL2.TransDetailID)
LEFT JOIN Station WITH(NOLOCK) ON TransDetail.GLDepartmentID = Station.ID
WHERE ( GL2.GLClassificationType IN (4000)
OR ( #ReportOn = 'B' AND GL2.GLAccountID in (12) )
OR ( #ReportOn = 'P' AND GL2.GLAccountID in (11,12) )
)
GROUP BY GL2.EntryDateTime,
GL2.GLAccountID,
GL2.GLAccountClassTypeID,
GL2.Classification,
GL2.GLClassificationType,
GL2.DivisionID,
GL2.IsTaxable,
GL2.TaxClassID,
GL2.GroupID,
-- TransHeader Related Fields
GL2.TransHeaderID,
TransHeader.OrderNumber,
COALESCE( TransHeader.InvoiceNumber, TransHeader.OrderNumber ),
TransHeader.CreditMemoOrderID,
TransHeader.Salesperson1ID,
TransHeader.OrderOriginID,
TransHeader.InvoiceAddressID,
TransHeader.PromotionID,
TransHeader.PricingLevelID,
Transheader.DiscountPrice,
TransHeader.OrderCreatedDate,
TransHeader.SaleDate,
TransHeader.ClosedDate,
TransHeader.BuiltDate,
TransHeader.StatusText,
TransHeader.DueDate,
TransHeader.OrderOriginName,
CAST(TransHeader.Description AS VARCHAR(30)),
-- TransDetail Related Fields
GL2.TransDetailID,
TransDetail.LineItemNumber,
TransDetail.Quantity,
GL2.GoodsItemID,
GL2.GoodsItemClassTypeID,
TransDetail.GoodsItemCode,
Station.StationName,
-- Account Related Fields
GL2.AccountID,
ParentAccount.CompanyName,
ParentAccount.AccountNumber,
ParentAccount.PricingPlanTypeID,
ParentAccount.IndustryID,
ParentAccount.RegionID,
ParentAccount.OriginID,
ParentAccount.Marketing3ID,
ParentAccount.BillingAddressID ) AS fx_Return
LEFT JOIN EmployeeGroup WITH(NOLOCK) ON EmployeeGroup.ID = fx_Return.DivisionID
LEFT JOIN MarketingListItem AS Origin WITH(NOLOCK) ON Origin.ID = fx_Return.CompanyOriginID
LEFT JOIN MarketingListItem AS CompanyOriginParent WITH(NOLOCK) ON Origin.ParentID = CompanyOriginParent.ID
AND Origin.ParentClassTypeID = CompanyOriginParent.ClassTypeID
LEFT JOIN MarketingListItem AS Industry WITH(NOLOCK) ON Industry.ID = fx_Return.IndustryID
LEFT JOIN MarketingListItem AS IndustryParent WITH(NOLOCK) ON Industry.ParentID = IndustryParent.ID
AND Industry.ParentClassTypeID = IndustryParent.ClassTypeID
LEFT JOIN MarketingListItem AS OrderOrigin WITH(NOLOCK) ON fx_Return.OrderOriginID = OrderOrigin.ID
LEFT JOIN MarketingListItem AS OrderOriginParent WITH(NOLOCK) ON OrderOrigin.ParentID = OrderOriginParent.ID
AND OrderOrigin.ParentClassTypeID = OrderOriginParent.ClassTypeID
LEFT JOIN Address WITH(NOLOCK) ON fx_Return.CompanyBillingAddressID = Address.ID
LEFT JOIN CustomerGoodsItem AS Product WITH(NOLOCK) ON fx_Return.GoodsItemID = Product.ID
AND Product.ClassTypeID=fx_Return.GoodsItemClassTypeID
LEFT JOIN PricingElement AS ProductCategory WITH(NOLOCK) ON Product.CategoryID = ProductCategory.ID
AND Product.CategoryClassTypeID = ProductCategory.ClassTypeID
LEFT JOIN PricingElement AS ProductSubCategory WITH(NOLOCK) ON ProductCategory.ParentID = ProductSubCategory.ID
AND ProductCategory.ParentClassTypeID = ProductSubCategory.ClassTypeID
LEFT JOIN Employee AS Salesperson1 WITH(NOLOCK) ON fx_Return.SalesPerson1ID = Salesperson1.ID
LEFT JOIN GLAccount WITH(NOLOCK) ON fx_Return.GLAccountID = GLAccount.ID
LEFT JOIN MarketingListItem AS Region WITH(NOLOCK) ON fx_Return.RegionID = Region.ID
) AS Orders
LEFT JOIN ( SELECT SUM( CASE
WHEN #ReportOn <> 'P' THEN -GL3.Amount
WHEN GL3.GLAccountID IN (11, 12, 51) THEN GL3.Amount
WHEN GL3.GLClassificationType IN (4000, 2005) THEN -GL3.Amount
ELSE 0
END ) AS CompanyTotalAmount,
COUNT(DISTINCT TransHeader.ID) AS CompanyOrderCount,
GL3.AccountID AS TotalsAccountID
FROM #GLEntries GL3
LEFT JOIN TransHeader WITH(NOLOCK) ON (TransHeader.ID = GL3.TransHeaderID)
WHERE ( GL3.GLClassificationType in (4000) -- 5002) --Kyle/Scott, we have no clue why this was included, can't think of any expense accounts you'd ever show as a sale
OR
( #ReportOn = 'B' AND GL3.GLAccountID in (12) )
OR
( #ReportOn = 'P' AND GL3.GLAccountID in (11, 12) )
)
GROUP BY GL3.AccountID ) AS Totals ON Totals.TotalsAccountID = Orders.AccountID
WHERE OrderNumber IS NOT NULL
1) OK - so you need to create a table with the same columns and same data types as in the select list (SELECT Orders.*, Totals.*...)
2) You will have to include the insert statement before the select - something like this
insert StagingTableName
select Orders.*, Totals.*...
3) Create a stored procedure with all your code in it.
4) Execute the stored procedure using a SQL Server Agent Job. This link should help.
Here is my sql query. I have column name "ExpenseBucketCoverage" in claim table in which I am storing bitwise operators store multiple values in one column like below
MED_COPAY = 1, MED_DED= 10, MED_COINS = 100, RX_COPAY = 1, RX_DED= 10, RX_COINS = 100
I want to replace hard coded value like MED_COPAY, MED_COINS, MED_DED, RX_DED, RX_COINS & RX_COPAY in query by using ExpenseBucketCoverage column value. Can some one please tell me how can I do that?
Someone has suggested me below soultion
retrieve data from claim and left joining the first matched record in eligibility. And then add custom code to loop through the datarows to split the rows by covered expense bucket, and set the service category code in-memory column based on the ExpenseBucketCoverage value for the claim.
SELECT
e.categoryid,
c.servicetype,
'II' AS RepordType,
e.TPAId AS TPA_Id,
e.EmployerCode,
e.SubscriberId,
e.MemberID,
c.ServiceFrom,
c.ServiceTo,
CASE
WHEN e.categoryid IN( 'MED_DED', 'RX_DED' ) THEN
deductible
WHEN e.categoryid IN( 'MED_COINS', 'RX_COINS' ) THEN
isnull(coins,0)
WHEN e.categoryid IN( 'MED_COPAY', 'RX_COPAY' ) THEN
copay
ELSE 0
END AS ClaimAmount,
'' AS AccountTypeCode,
'1' ClaimsCrossoverAutoPay,
e.CategoryId,
CASE c.ServiceType
WHEN 'H' THEN
CASE e.PayeeIndicator
WHEN 'N' THEN '0'
WHEN 'Y' THEN '1'
END
WHEN 'P' THEN '0'
END AS PayProvider,
CASE c.ServiceType
WHEN 'H' THEN
CASE PayeeIndicator
WHEN 'N' THEN '0'
WHEN 'Y' THEN '1'
END
WHEN 'P' THEN '0'
END AS ReimbursementMethod,
CASE c.ServiceType
WHEN 'H' THEN c.Provider
WHEN 'P' THEN ''
END AS ProviderId,
'1' EnforceAccountEffectiveDates,
c.Id,
c.ClaimNumber + e.CategoryId as 'ExternalClaimNumber',
c.ProviderName,
c.CarrierId + ';' + c.SourceClaimNumber AS Notes
FROM Claim c
INNER JOIN Eligibility e ON e.TPAId = c.TPAId AND e.EIN = c.EIN AND
c.Processed = 'Y' AND e.FilterType = 'Eligibility'
AND c.TPAId='PrimePay'
AND (c.ServiceFrom >= e.BenefitEffectiveDate
AND c.ServiceFrom <=e.BenefitTermDate)
AND ( ( c.PayorID = c.PatientSSN
AND e.SubscriberSSN = c.PatientSSN
AND (c.EmployeeFirstName = c.PatientFirstName
AND c.EmployeeLastName = c.PatientLastName)
AND(e.MemberSSN = '' OR e.MemberSSN = NULL)
AND(e.MemberFirstName = '' OR e.MemberFirstName = NULL)
AND(e.MemberLastName = '' OR e.MemberLastName = NULL))
OR((c.PayorID != c.PatientSSN AND e.MemberSSN = c.PatientSSN
AND e.MemberFirstName = c.PatientFirstName
AND e.MemberLastName = c.PatientLastName)
OR(c.PayorID != c.PatientSSN AND e.MemberFirstName = c.PatientFirstName
AND e.MemberLastName= c.PatientLastName)))
AND (( c.Servicetype ='P'
AND e.CategoryID IN('RX_COINS','RX_COPAY', 'RX_DED' ))
OR ( c.Servicetype = 'H'
AND e.CategoryID IN( 'MED_COINS','MED_COPAY', 'MED_DED' )))