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

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)

Related

Why does sum totals differ in query?

with totals as (select two_sim_ind,
case when account_type_key in(86,88,13,113,37,39,131) then 'B2C' else 'B2B' end as Segment,
case when subs_activation_date_key >= time_key then 'New' else 'Old' end as Sales_to_active,
time_key as TIME_KEY, name_region as REGION, area_name as DISTRICT, sim_type as USIM_FLAG,
case when lte_device = 1 or lte_ind in('Yes') or lte_user > 0 then '4G Device'
when ind_3g in('Yes') and lte_ind in('No') then '3G Device' else '2G Device' end as device_tech_support,
device_type as DEVICE_TYPE,
case when device_type in('Smartphone') then 'Yes' else 'No' end as is_Smartphone_AAB,
case when data_user in(0) then 'No' else 'Yes' end as is_Data_User,
case when lte_user in(0) then 'No' else 'Yes' end as is_4G_Data_User,
count(distinct subs_key) as A1M,
sum(total_revenue) as REVENUE_TOTAL,
sum(data_traffic_local_2g + data_traffic_local_3g+data_traffic_local_4g) as TRAFFIC_DATA_full_Sum,
sum(data_traffic_local_2g + data_traffic_local_3g) as g2_g3_traffic,
sum(data_traffic_local_4g) as Data_traffic_4g
from dwh.m as m
left join (select model_name, ind_3g, lte_ind
from dwh.w) as devices
on m.model_name = devices.model_name
where rtc_active_ind > 0 and subs_status_key in ('A', 'S')
and (time_key >= '2021-12-01' and time_key <= '2021-12-01')
group by two_sim_ind,
case when account_type_key in(86,88,13,113,37,39,131) then 'B2C' else 'B2B' end,
case when subs_activation_date_key >= time_key then 'New' else 'Old' end,
case when data_user in(0) then 'No' else 'Yes' end,
case when lte_device = 1 or lte_ind in('Yes') or lte_user > 0 then '4G Device'
when ind_3g in('Yes') and lte_ind in('No') then '3G Device' else '2G Device' end,
time_key, name_region, area_name, sim_type, device_type, lte_user)
select REGION, sum(REVENUE_TOTAL)
from totals
group by REGION
When I aggregate total of all records by region, value is significantly higher than it should be.
Result I get:
select name_region as REGION, sum(total_revenue)
from dwh.m
where (time_key >= '2021-12-01' and time_key <= '2021-12-01')
and rtc_active_ind > 0 and subs_status_key in ('A', 'S')
group by name_region;
Result of query and what I need:
Something happens to individual records when grouping by? What could be the reason?

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';

Nested CASE statements in SQL

I am running the below SQL and I need to add a case statement for the svcState column.
I have a value defined for each number in that column which I need to have in my query. For instance 7 is OK, 4 is down etc. I tried adding this in the CASE statement as below and it seems, the syntax is incorrect. Any help will be greatly appreciated.
SELECT * FROM
(
SELECT
A.NodeName AS NodeName,
MAX(CASE WHEN Poller_Name='svcServiceName' THEN CAST(Status AS varchar) ELSE ''END) svcServiceName,
MAX(CASE (CASE WHEN Poller_Name='svcState' AND Status ='7' THEN 'OK'
WHEN Poller_Name='svcstate' AND Status ='4' THEN 'OUT OF SERVICE' END)
THEN CAST(Status AS bigint) ELSE '' END) svcState
FROM
(
SELECT
Nodes.Caption AS NodeName, CustomNodePollers_CustomPollers.UniqueName AS Poller_Name, CustomNodePollerStatus_CustomPollerStatus.Status AS Status, CustomNodePollerStatus_CustomPollerStatus.rowid as row, CustomNodePollerStatus_CustomPollerStatus.RawStatus as RawStatus
FROM
((Nodes INNER JOIN CustomPollerAssignment CustomNodePollerAssignment_CustomPollerAssignment ON (Nodes.NodeID = CustomNodePollerAssignment_CustomPollerAssignment.NodeID)) INNER JOIN CustomPollers CustomNodePollers_CustomPollers ON (CustomNodePollerAssignment_CustomPollerAssignment.CustomPollerID = CustomNodePollers_CustomPollers.CustomPollerID)) INNER JOIN CustomPollerStatus CustomNodePollerStatus_CustomPollerStatus ON (CustomNodePollerAssignment_CustomPollerAssignment.CustomPollerAssignmentID = CustomNodePollerStatus_CustomPollerStatus.CustomPollerAssignmentID)
WHERE
(
(CustomNodePollers_CustomPollers.UniqueName = 'svcServiceName') OR
(CustomNodePollers_CustomPollers.UniqueName = 'svcState')
)
AND
(
(CustomNodePollerAssignment_CustomPollerAssignment.InterfaceID = 0)
)
and Nodes.Caption = '101'
)A
GROUP BY NodeName, row
--ORDER BY svcServiceName
) B
Desired Output
MAX(CASE WHEN Poller_Name = 'svcState' THEN (CASE WHEN status = '7' THEN 'OK' ELSE 'DOWN' END) END)
Or...
MAX(CASE WHEN Poller_Name = 'svcState' AND status = '7' THEN 'OK'
WHEN Poller_Name = 'svcState' AND status = '4' THEN 'DOWN' END)
Or...
MAX(CASE WHEN Poller_Name != 'svcState' THEN NULL -- Assumes the poller_name is never NULL
WHEN status = '7' THEN 'OK'
WHEN status = '4' THEN 'DOWN'
END)
Where there is no ELSE specified, it is implicitly ELSE NULL, and NULL values are skipped by the MAX().

How to filter by year for some period columns

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())

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