How to filter by year for some period columns - sql

I'm trying to pull a report of the previous year's usage based on Year and Period(month)
I adjusted the top line to add a filter for AND demand_period.year_for_period = YEAR(getdate()) but then realized that it will also remove the possibility of last year's results.
Prior to adding the YEAR statement, it was providing full sums of the usage for all years, broken down by month.
Here's what I have so far:
SELECT (inv_mast.item_id) as [Item ID]
,inv_mast.item_desc as [Item Description]
,address.name as [Prim Supplier Name]
,SUM(CASE WHEN (demand_period.period = MONTH(getdate()) AND demand_period.year_for_period = YEAR(getdate()))THEN inv_period_usage ELSE 0 END) AS [Period1Usage]
,SUM(CASE WHEN demand_period.period = '2' THEN inv_period_usage ELSE 0 END) AS [Period2Usage]
,SUM(CASE WHEN demand_period.period = '3' THEN inv_period_usage ELSE 0 END) AS [Period3Usage]
,SUM(CASE WHEN demand_period.period = '4' THEN inv_period_usage ELSE 0 END) AS [Period4Usage]
,SUM(CASE WHEN demand_period.period = '5' THEN inv_period_usage ELSE 0 END) AS [Period5Usage]
,SUM(CASE WHEN demand_period.period = '6' THEN inv_period_usage ELSE 0 END) AS [Period6Usage]
,SUM(CASE WHEN demand_period.period = '7' THEN inv_period_usage ELSE 0 END) AS [Period7Usage]
,SUM(CASE WHEN demand_period.period = '8' THEN inv_period_usage ELSE 0 END) AS [Period8Usage]
,SUM(CASE WHEN demand_period.period = '9' THEN inv_period_usage ELSE 0 END) AS [Period9Usage]
,SUM(CASE WHEN demand_period.period = '10' THEN inv_period_usage ELSE 0 END) AS [Period10Usage]
,SUM(CASE WHEN demand_period.period = '11' THEN inv_period_usage ELSE 0 END) AS [Period11Usage]
,SUM(CASE WHEN demand_period.period = '12' THEN inv_period_usage ELSE 0 END) AS [Period12Usage]
FROM inv_mast
JOIN inv_loc ON inv_loc.inv_mast_uid = inv_mast.inv_mast_uid
JOIN inventory_supplier_x_loc ON inventory_supplier_x_loc.location_id = inv_loc.location_id
JOIN inventory_supplier ON inventory_supplier.inventory_supplier_uid = inventory_supplier_x_loc.inventory_supplier_uid
JOIN supplier ON supplier.supplier_id = inventory_supplier.supplier_id
JOIN address ON (address.id = supplier.supplier_id)
JOIN inv_period_usage ON inv_period_usage.location_id = inv_loc.location_id
JOIN demand_period ON (inv_period_usage.demand_period_uid = demand_period.demand_period_uid)
WHERE
(inv_loc.location_id = '100001')
AND (inventory_supplier_x_loc.primary_supplier = 'Y')
AND (inv_mast.item_id = '111')
GROUP BY item_id, item_desc, name
How could I edit the SELECT statements to include the last 12 months, including if they are in a previous year?
Thank you for your help!

Add this:
and demand_period.year_for_period >= DATEADD(month, -12, getdate())

Related

Copy weird values from a column with where statement in SQL Oracle

Hello I have a record that has a SQL in a column. I would like to copy the values and update it to a similar record that shows null for that column. I keep getting a missing comma error.
I am trying 'SET' HDR_LBL_SQL for WHSE 1 like WHSE 2. Any ideas? Thanks
Table: Label_Cnfg
Fields: WHSE, TYPE, HDR_LBL_SQL
WHSE
TYPE
HDR_LBL_SQL
1
TICKET
NULL
2
TICKET
(*See SQL Below)
HDR_LBL_SQL for WHSE 1
Select
ch.case_nbr,
ch.case_nbr case_brcd,
ch.RCVD_SHPMT_NBR,
iwm.PUTWY_TYPE ,
ch.PO_NBR,
(CASE WHEN CASECNT.SKUCOUNT = '1' THEN to_char(ch.MFG_DATE,'MM-DD-YYYY') ELSE 'MIXED' END) MFG_DATE,
(CASE WHEN CASECNT.SKUCOUNT = '1' THEN to_char(ch.XPIRE_DATE,'MM-DD-YYYY') ELSE 'MIXED' END)XPIRE_DATE,
(CASE WHEN CASECNT.SKUCOUNT = '1' THEN to_char(ch.CONS_PRTY_DATE,'MM-DD-YYYY') ELSE 'MIXED' END) CONS_PRTY_DATE,
(CASE WHEN CASECNT.SKUCOUNT = '1' THEN trim(im.dsp_sku) ELSE 'MIXED' END) SKU,
(CASE WHEN CASECNT.SKUCOUNT = '1' THEN trim(im.dsp_sku) ELSE 'MIXED' END) SKU_BRCD,
(CASE WHEN CASECNT.SKUCOUNT = '1' THEN im.sku_desc ELSE 'MIXED' END) SKU_DESC,
(CASE WHEN CASECNT.SKUCOUNT = '1' THEN CD.INVN_TYPE ELSE 'MIXED' END) INVN_TYPE,
(CASE WHEN CASECNT.SKUCOUNT = '1' THEN CD.INVN_TYPE ELSE 'MIXED' END) BRCD_INVN_TYPE,
(CASE WHEN CASECNT.SKUCOUNT = '1' THEN cd.PROD_STAT ELSE 'MIXED' END) PROD_STAT,
(CASE WHEN CASECNT.SKUCOUNT = '1' THEN cd.PROD_STAT ELSE 'MIXED' END) BRCD_PROD_STAT,
(CASE WHEN CASECNT.SKUCOUNT = '1' THEN cd.batch_nbr ELSE 'MIXED' END) batch_nbr,
(CASE WHEN CASECNT.SKUCOUNT = '1' THEN cd.batch_nbr ELSE 'MIXED' END) BRCD_batch_nbr,
(CASE WHEN CASECNT.SKUCOUNT = '1' THEN cd.CNTRY_OF_ORGN ELSE 'MIXED' END) CNTRY_OF_ORGN,
(CASE WHEN CASECNT.SKUCOUNT = '1' THEN cd.CNTRY_OF_ORGN ELSE 'MIXED' END) BRCD_CNTRY_OF_ORGN,
SUM(cd.actl_qty),' ',' ',' ',' ',' '
from
case_hdr ch
inner join case_dtl cd on ch.case_nbr = cd.case_nbr
inner join item_master im on im.sku_id = cd.sku_id
inner join item_whse_master iwm on im.sku_id = iwm.sku_id
inner join (select count(distinct(SKU_ID||INVN_TYPE||PROD_STAT||BATCH_NBR)) SKUCOUNT,case_nbr from case_dtl cd where case_nbr = :g_case_nbr group by case_nbr)CASECNT
on CASECNT.case_nbr = cd.case_nbr
where
ch.case_nbr = :g_case_nbr
and cd.case_seq_nbr = :g_case_seq_nbr
and ch.stat_code in ( '10', '30', '90', '96' )
group by
ch.case_nbr,
ch.case_nbr ,
ch.RCVD_SHPMT_NBR,
ch.PO_NBR,
iwm.PUTWY_TYPE ,
(CASE WHEN CASECNT.SKUCOUNT = '1' THEN to_char(ch.MFG_DATE,'MM-DD-YYYY') ELSE 'MIXED' END) ,
(CASE WHEN CASECNT.SKUCOUNT = '1' THEN to_char(ch.XPIRE_DATE,'MM-DD-YYYY') ELSE 'MIXED' END),
(CASE WHEN CASECNT.SKUCOUNT = '1' THEN to_char(ch.CONS_PRTY_DATE,'MM-DD-YYYY') ELSE 'MIXED' END) ,
(CASE WHEN CASECNT.SKUCOUNT = '1' THEN trim(im.dsp_sku) ELSE 'MIXED' END) ,
(CASE WHEN CASECNT.SKUCOUNT = '1' THEN trim(im.dsp_sku) ELSE 'MIXED' END) ,
(CASE WHEN CASECNT.SKUCOUNT = '1' THEN im.sku_desc ELSE 'MIXED' END),
(CASE WHEN CASECNT.SKUCOUNT = '1' THEN CD.INVN_TYPE ELSE 'MIXED' END),
(CASE WHEN CASECNT.SKUCOUNT = '1' THEN cd.PROD_STAT ELSE 'MIXED' END),
(CASE WHEN CASECNT.SKUCOUNT = '1' THEN cd.batch_nbr ELSE 'MIXED' END),
(CASE WHEN CASECNT.SKUCOUNT = '1' THEN cd.CNTRY_OF_ORGN ELSE 'MIXED' END)
You can do something like:
update Label_Cnfg set
HDR_LBL_SQL=(select HDR_LBL_SQL from Label_Cnfg where WHSE=2 and TYPE='TICKET')
where WHSE=1 and TYPE='TICKET';

Summary result from referring tables

I Have some database tables.one table call GL and has gl_id, gl_type_id, etc. columns.
Other one is gl_tran table and has gl_id, trn_amount, etc. I want to get a summary of gl_type_id of tran_amount. I wrote a query for this.
SELECT GL.CHAT_ACC_ID,GL.CHAT_ACC_NAME,GL.GL_TYPE_ID,GL.GL_TYPE_NAME,
SUM(CASE WHEN tr.CR_DR = 'CR' AND TR.BRANCH_CODE=1000 AND TR.TRAN_DATE<'2000-01-01' THEN TR.GL_TRN_AMT ELSE 0
END) AS CR_BEFORE,
SUM(CASE WHEN tr.CR_DR='DR' AND TR.BRANCH_CODE=1000 AND TR.TRAN_DATE<'2000-01-01' THEN TR.GL_TRN_AMT ELSE 0
END) AS DR_BEFORE,
SUM(CASE WHEN tr.CR_DR = 'CR' AND TR.BRANCH_CODE=1000 AND TR.TRAN_DATE BETWEEN '2000-01-01' AND '2010-01-01' THEN TR.GL_TRN_AMT ELSE 0
END) AS CR_BETWEEN,
SUM(CASE WHEN tr.CR_DR = 'DR' AND TR.BRANCH_CODE=1000 AND TR.TRAN_DATE BETWEEN '2000-01-01' AND '2010-01-01' THEN TR.GL_TRN_AMT ELSE 0
END) AS DR_BETWEEN
FROM [COREBANKER1].[dbo].[GL_MAIN] as GL
LEFT JOIN [COREBANKER1].[dbo].[GL_DAILY_TRN] AS TR ON GL.GL_ID = TR.GL_CODE
GROUP BY GL.CHAT_ACC_ID,GL.CHAT_ACC_NAME,GL.GL_TYPE_ID,GL.GL_TYPE_NAME
ORDER BY GL.GL_ID
But this result has only if transaction happens for particular gl. I want summary for all GL.CHAT_ACC_ID. How should I change my query for that result?
I think you just need to add below statement in select...
Sum(TR.GL_TRN_AMT) over() as TotalSum
I found the solution... :D
SELECT CG.CHART_ACC_ID,CG.CHART_ACC_NAME,CG.GL_TYPE_ID,CG.GL_TYPE_NAME,
SUM(CASE WHEN tr.CR_DR = 'CR' AND TR.BRANCH_CODE=1000 AND TR.TRAN_DATE<'2000-01-01' AND CG.CHART_ACC_ID=GL.CHAT_ACC_ID AND TR.GL_CODE=GL.GL_ID THEN TR.GL_TRN_AMT ELSE 0
END) AS CR_BEFORE,
SUM(CASE WHEN tr.CR_DR='DR' AND TR.BRANCH_CODE=1000 AND TR.TRAN_DATE<'2000-01-01' AND CG.CHART_ACC_ID=GL.CHAT_ACC_ID AND TR.GL_CODE=GL.GL_ID THEN TR.GL_TRN_AMT ELSE 0
END) AS DR_BEFORE,
SUM(CASE WHEN tr.CR_DR = 'CR' AND TR.BRANCH_CODE=1000 AND TR.TRAN_DATE BETWEEN '2000-01-01' AND '2010-01-01' AND CG.CHART_ACC_ID=GL.CHAT_ACC_ID AND TR.GL_CODE=GL.GL_ID THEN TR.GL_TRN_AMT ELSE 0
END) AS CR_BETWEEN,
SUM(CASE WHEN tr.CR_DR = 'DR' AND TR.BRANCH_CODE=1000 AND TR.TRAN_DATE BETWEEN '2000-01-01' AND '2010-01-01' AND CG.CHART_ACC_ID=GL.CHAT_ACC_ID AND TR.GL_CODE=GL.GL_ID THEN TR.GL_TRN_AMT ELSE 0
END) AS DR_BETWEEN
FROM[COREBANKER1].[dbo].[GL_DAILY_TRN] AS TR, [COREBANKER1].[dbo].[GL_MAIN] as GL full JOIN [COREBANKER1].[dbo].GL_CHART_ACC AS CG
ON GL.CHAT_ACC_ID=CG.CHART_ACC_ID
GROUP BY CG.CHART_ACC_ID,CG.CHART_ACC_NAME,CG.GL_TYPE_ID,CG.GL_TYPE_NAME
ORDER BY CG.CHART_ACC_ID

How do I GROUP the results of a query that is already grouped?

I have a query:
SELECT
CONVERT(varchar(7),SUBMITDATE, 120) as 'Month'
,CASE WHEN ReportType = '1' THEN (SELECT AVG(DATEDIFF(DAY,SUBMITDATE,DateClosed))) END as 'Report1Avg'
,CASE WHEN ReportType = '2' THEN (SELECT AVG(DATEDIFF(DAY,SUBMITDATE,DateClosed))) END as 'Report2Avg'
,CASE WHEN ReportType = '3' THEN (SELECT AVG(DATEDIFF(DAY,SUBMITDATE,DateClosed))) END as 'Report3Avg'
,CASE WHEN ReportType = '4' THEN (SELECT AVG(DATEDIFF(DAY,SUBMITDATE,DateClosed))) END as 'Report4Avg'
,CASE WHEN ReportType = '5' THEN (SELECT AVG(DATEDIFF(DAY,SUBMITDATE,DateClosed))) END as 'Report5Avg'
FROM Table1
WHERE STATUS = 'Closed'
GROUP BY CONVERT(varchar(7),SUBMITDATE, 120), ReportType
ORDER BY CONVERT(varchar(7),SUBMITDATE, 120)
Which produces the following result:
My question is: How do I consolidate the results of each month in one row?
ex. for '2015-06', I have 3 rows of results.
Is this possible?
Use avg around the case expression. Also use else 0 to avoid null values.
SELECT
CONVERT(varchar(7),SUBMITDATE, 120) as 'Month'
,AVG(CASE WHEN ReportType = '1' THEN DATEDIFF(DAY,SUBMITDATE,DateClosed) ELSE 0 END) as 'Report1Avg'
,AVG(CASE WHEN ReportType = '2' THEN DATEDIFF(DAY,SUBMITDATE,DateClosed) ELSE 0 END) as 'Report2Avg'
,AVG(CASE WHEN ReportType = '3' THEN DATEDIFF(DAY,SUBMITDATE,DateClosed) ELSE 0 END) as 'Report3Avg'
,AVG(CASE WHEN ReportType = '4' THEN DATEDIFF(DAY,SUBMITDATE,DateClosed) ELSE 0 END) as 'Report4Avg'
,AVG(CASE WHEN ReportType = '5' THEN DATEDIFF(DAY,SUBMITDATE,DateClosed) ELSE 0 END) as 'Report5Avg'
FROM Table1
WHERE STATUS = 'Closed'
GROUP BY CONVERT(varchar(7),SUBMITDATE, 120)
ORDER BY CONVERT(varchar(7),SUBMITDATE, 120)

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

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