Dynamicaly Naming Columns - Using SQL server 2008 - sql

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

Related

SQL code to set a specific date as compared to "today's" date

In the first column (Report_Date) of this query the date is being constructed and is today's day, and is used in the following lines to select is the following columns. I'd like to use a specific day in the query.
I'd like help to write the format to replace column 1 (Report_Date) with a different date to create aging, like June 1st - 2021-06-01.
SELECT
convert(datetime,convert(char,datepart(mm,getdate()))+'/'+convert(char,datepart(dd,getdate()))+'/'+convert(char,datepart(yyyy,getdate())))Report_Date,
sum(case
when datediff(dd, (convert(datetime,convert(char,B.Original_Bill_Date,101))), getdate())
Between 0 and 30 then B.CurrentBalance else 0
end) '0-30',
sum(case
when datediff(dd, (convert(datetime,convert(char,B.Original_Bill_Date,101))), getdate())
Between 31 and 60 then B.CurrentBalance else 0
end) '31-60',
sum(case
when datediff(dd, (convert(datetime,convert(char,B.Original_Bill_Date,101))), getdate())
Between 61 and 90 then B.CurrentBalance else 0
end) '61-90',
sum(case
when datediff(dd, (convert(datetime,convert(char,B.Original_Bill_Date,101))), getdate())
Between 91 and 120 then B.CurrentBalance else 0
end) '91-120',
B.Primary_Payer_Code,
B.Secondary_Payer_Code,
B.CurrentResponsibility_desc,
Case When G.PAYER_GROUP IS NOT NULL Then G.PAYER_GROUP
Else Case When B.Primary_Payer_Code = 'PP' Then 'SELF PAY' Else
F.Description End End
FROM
Date D with (nolock)
JOIN TEL_BILLED_LINE_ITEM_ODS B with (nolock) ON ( convert(datetime,convert(char,B.Original_Bill_Date,101)) = D.DATE)
LEFT OUTER JOIN TBLPAYER_ODS P with (nolock) ON B.Primary_Payer_Code=P.Code
LEFT OUTER JOIN TBLFINANCIALCLASS_ODS F with (nolock) ON F.tblfinancialclassid = P.FinancialClassID
LEFT OUTER JOIN PAYER_GROUP G ON G.PAYER_CODE = P.CODE
WHERE
( B.CurrentBalance != 0)
AND B.BadDebtFlagYN=0
AND B.Primary_Payer_Code !='CL' -- exclude CLIENT 07/01/2010 jdw
GROUP BY
B.Primary_Payer_Code,
B.Secondary_Payer_Code,
B.CurrentResponsibility_desc,
Case When G.PAYER_GROUP IS NOT NULL Then G.PAYER_GROUP
Else Case When B.Primary_Payer_Code = 'PP' Then 'SELF PAY' Else
F.Description End End

How to filter columns in addition to summing up in sql developer?

I wrote this code to get the number of risks with different status but I don't want the result in multiple rows, I just added the C_INSERTTIME field in order to filter the time later. how can i get the result in one row?
SELECT rsk.C_INSERTTIME inserttime,
SUM(CASE
WHEN rskst.c_code = 'HSE_RISK_STATUS_DRAFT' THEN 1
ELSE 0
END) AS drafted_risk,
SUM(CASE
WHEN rskst.c_code <> 'HSE_RISK_STATUS_DRAFT' THEN 1
ELSE 0
END) AS analyzed_risk,
SUM(CASE
WHEN rskdecsass.c_code = 'HSE_DECISION_ASSESSMENT_APPROVED' THEN 1
ELSE 0
END) AS approved_assessed_risks
FROM T_HSE_RISK rsk
LEFT JOIN t_hse_category_element rskst ON rskst.c_id = rsk.f_category_element_id_rsk_stts
LEFT JOIN t_hse_category_element rskdecsass ON rskdecsass.c_id = rsk.F_CTGRY_ELMNT_ID_DCSN_ASSSSMNT
WHERE rsk.C_INSERTTIME >= TIMESTAMP '2000-01-01 00:00:00'
GROUP BY rsk.C_INSERTTIME
You should remove the GROUP BY and use aggregation on C_inserttime as follows:
SELECT min(rsk.C_INSERTTIME) inserttime, -- or max
SUM(CASE
WHEN rskst.c_code = 'HSE_RISK_STATUS_DRAFT' THEN 1
ELSE 0
END) AS drafted_risk,
SUM(CASE
WHEN rskst.c_code <> 'HSE_RISK_STATUS_DRAFT' THEN 1
ELSE 0
END) AS analyzed_risk,
SUM(CASE
WHEN rskdecsass.c_code = 'HSE_DECISION_ASSESSMENT_APPROVED' THEN 1
ELSE 0
END) AS approved_assessed_risks
FROM T_HSE_RISK rsk
LEFT JOIN t_hse_category_element rskst ON rskst.c_id = rsk.f_category_element_id_rsk_stts
LEFT JOIN t_hse_category_element rskdecsass ON rskdecsass.c_id = rsk.F_CTGRY_ELMNT_ID_DCSN_ASSSSMNT
WHERE rsk.C_INSERTTIME >= TIMESTAMP '2000-01-01 00:00:00'
-- GROUP BY rsk.C_INSERTTIME -- removed this

SQL Year over Year Performance with Criteria

I am trying to return year over year results based on date criteria. There is additional information I would like to include in the query i.e. first date of activity and first date of activity with spot name like '%6%'. The current query I have is multiplying the correct amounts by 6 and I can't figure out how to solve. When I remove the first "where" clause I get the correct amounts. Any help would be appreciated.
Select
V.IGB_License,
DBA,
V.Sci_Games_Name,
convert(date,v2.Activity_date) as First6thMachineDate,
convert(date,V3.Activity_date) as GoLiveDate,
sum(case when (v.Activity_date between '1/23/2019' and DATEADD(YEAR,-2,getdate()-1)) then v.Funds_in else 0 end) as FundsIn2019,
sum(case when (v.Activity_date between '1/23/2020' and DATEADD(YEAR,-1,getdate()-1)) then v.Funds_in else 0 end) as FundsIn2020,
sum(case when (v.Activity_date between '1/23/2021' and getdate()) then v.Funds_in else 0 end) as FundsIn2021,
sum(case when (v.Activity_date between '1/23/2019' and DATEADD(YEAR,-2,getdate()-1)) then v.Net_funds else 0 end) as NetFunds2019,
sum(case when (v.Activity_date between '1/23/2020' and DATEADD(YEAR,-1,getdate()-1)) then v.Net_funds else 0 end) as NetFunds2020,
sum(case when (v.Activity_date between '1/23/2021' and getdate()) then v.Net_funds else 0 end) as NetFunds2021
From VGT_activity V
Left Join Locations on v.IGB_License = Locations.IGB_License
left join VGT_activity V2 on v.IGB_License = v2.IGB_License
Left join VGT_activity V3 on v.IGB_License = v3.IGB_License
Where v2.Activity_date = (
Select Min(V1.Activity_date)
From VGT_activity V1
Where v1.IGB_License = V2.IGB_License
and Spot_name like '%6%'
)
and v3.Activity_date = (
Select Min(V1.Activity_date)
From VGT_activity V1
Where v1.IGB_License = V3.IGB_License
)
group by V.IGB_License, dba, V.Sci_Games_Name, v2.Activity_date, v3.Activity_date
order by 4

Update a complex SQL query to add a new column with the sum of two columns

The below SQL query creates a table with n number of columns named in the next line.
...., curr_amount, tax_amount, ....
I am having a very tough time updating the below query to create a new column called total and position it exactly after tax_amount column and the total column should contain the values that are obtained after sum of curr_amount & tax_amount.
I have been working on this from more than one day but couldn't figure it out.
P.S. Still a noob here. Thanks alot for your time.
.
SELECT Isnull(t.total_month, 'Total') total_month,
t.tax_amount,
t.curr_amount,
t.usage_qty,
t.kh_qty,
t.bill_cnt
FROM (SELECT dbo.Sigmadf(bm.posted_date, 'YYYY-MM') total_month,
Sum(CASE
WHEN rr.usage_qty IS NULL THEN 0
ELSE Cast (rr.usage_qty AS NUMERIC(18, 2))
END) usage_qty,
Sum(CASE
WHEN bm.curr_amount IS NULL THEN 0
ELSE bm.curr_amount
END) curr_amount,
Sum(CASE
WHEN bm.adj_amount IS NULL THEN 0
ELSE bm.adj_amount
END) adj_amount,
Sum(CASE
WHEN bm.bal_fwd_amount IS NULL THEN 0
ELSE bm.bal_fwd_amount
END) bal_forward,
Sum(CASE
WHEN bm.tax_amount IS NULL THEN 0
ELSE bm.tax_amount
END) tax_amount,
Sum(CASE
WHEN bm.due_amount IS NULL THEN 0
ELSE bm.due_amount
END) due_amount,
Sum(CASE
WHEN bm.last_total_paid_amount IS NULL THEN 0
ELSE bm.last_total_paid_amount * -1
END) paid_amount,
Sum(CASE
WHEN bm.bill_print = 'Y' THEN 1
ELSE 0
END) pdf_cnt,
Sum(CASE
WHEN Isnull(bm.bill_handling_code, '0') = '0' THEN 1
ELSE 0
END) reg_cnt,
Sum(CASE
WHEN Isnull(bm.bill_handling_code, '0') = '1' THEN 1
ELSE 0
END) ftime_cnt,
Sum(CASE
WHEN Isnull(bm.bill_handling_code, '0') = '9999' THEN 1
ELSE 0
END) ltime_cnt,
Count(*) bill_cnt,
Sum(CASE
WHEN bill_status = '01' THEN 1
ELSE 0
END) canc_cnt,
Sum(CASE
WHEN bill_status = '01' THEN
CASE
WHEN rr.usage_qty IS NULL THEN 0
ELSE Cast (rr.usage_qty AS NUMERIC(18, 2))
END
ELSE 0
END) canc_usg,
Sum(CASE
WHEN vis.kh_qty IS NULL THEN 0
ELSE Cast(vis.kh_qty AS NUMERIC(18, 2))
END) kh_qty
FROM bill_master bm WITH (nolock)
INNER JOIN (SELECT bill_no,
Sum(CASE
WHEN vpb.recurr_charge_type IN ( 'T4',
'SLF' )
THEN
CASE
WHEN vpb.print_qty = 'Y'
AND vpb.usage_qty IS NOT NULL
THEN
Cast (vpb.usage_qty AS
NUMERIC(18, 2))
ELSE 0
END
ELSE 0
END) usage_qty
FROM v_print_bills_all vpb
GROUP BY bill_no) rr
ON rr.bill_no = bm.bill_no
LEFT OUTER JOIN vis_bill_master_cr vis WITH (nolock)
ON bm.bill_no = vis.bill_no
WHERE 1 = 1
AND dbo.Trunc(bm.posted_date) >= '20150101'
AND dbo.Trunc(bm.posted_date) <= '20151124'
AND bm.posted_date IS NOT NULL
AND bm.cust_id NOT IN (SELECT cc.code_type cust_id
FROM code_table cc WITH (nolock)
WHERE cc.code_tabname = 'RptExclCust'
AND cc.code_value = 'cust_id')
GROUP BY dbo.Sigmadf(bm.posted_date, 'YYYY-MM') WITH rollup)t
I must say that the explanation is not so clear.
From my understanding, you want the total of two columns.
So, wrap all your query between parenthesis, call it subQuery, and make the sum of the two columns on top:
SELECT subQuery.total_month as bill_date,
subQuery.curr_amount as amount,
subQuery.tax_amount tax,
subQuery.curr_amount + subQuery.tax_amount as [total],
...
FROM
(..your entire query here..) as subQuery

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