Function to split value between columns in access - sql

I have the following table:
And I need to split the value column into two columns based on the value of the status column, also add a difference between the two. Like This:
I was able to split it by using two separate queries, but when I merge them together I get duplicate values, even If I use the Sum and group by the costumer.

You can sue conditional aggregation:
select customer,
sum(iif(status = 'debt', value, 0)) as debt,
sum(iif(status = 'pay', value, 0)) as pay
(sum(iif(status = 'debt', value, 0)) -
sum(iif(status = 'pay', value, 0))
) as diff
from t
group by customer;

Try this please
tb1: Customer, value, status
select d.Customer, d.value as debt, IIf(p.value Is Null, 0, p.value) as pay, d.value - IIf(p.value Is Null, 0, p.value) as diff
from
(select Customer, value from tb1 where status = 'debt')d
left join
(select Customer, value from tb1 where status = 'pay')p on d.Customer = p.Customer

With a LEFT self join:
select t.Customer,
t.[value] as debt, tt.[value] as pay, t.[value] - Nz(tt.[value]) as diff
from tablename t left join tablename tt
on tt.customer = t.customer and t.[status] <> tt.[status]
where t.[status] = 'debt'
Results:
Customer debt pay diff
Fernando 445 445 0
Marcelo 332 123 209
Adriana 889 889

Related

Query error: Column name ICUSTAY_ID is ambiguous. Using multiple subqueries in BigQuery

Hi, I receive the following query error "Query error: Column name ICUSTAY_ID is ambiguous" referred to the third last line of code (see the following code). Please can you help me? Thank you so much!
I am an SQL beginner..
WITH t AS
(
SELECT
*
FROM
(
SELECT *,
DATETIME_DIFF(CHARTTIME, INTIME, MINUTE) AS pi_recorded
FROM
(
SELECT
*
FROM
(
SELECT * FROM
(SELECT i.SUBJECT_ID, p.dob, i.hadm_id, p.GENDER, a.ETHNICITY, a.ADMITTIME, a.INSURANCE, i.ICUSTAY_ID,
i.DBSOURCE, i.INTIME, DATETIME_DIFF(a.ADMITTIME, p.DOB, DAY) AS age,
CASE
WHEN DATETIME_DIFF(a.ADMITTIME, p.DOB, DAY) <= 32485
THEN 'adult'
WHEN DATETIME_DIFF(a.ADMITTIME, p.DOB, DAY) > 32485
then '>89'
END AS age_group
FROM `project.mimic3.ICUSTAYS` AS i
INNER JOIN `project.mimic3.PATIENTS` AS p ON i.SUBJECT_ID = p.SUBJECT_ID
INNER JOIN `project.mimic3.ADMISSIONS` AS a ON i.HADM_ID = a.HADM_ID)
WHERE age >= 6570
) AS t1
LEFT JOIN
(
SELECT ITEMID, ICUSTAY_ID, CHARTTIME, VALUE, FROM `project.mimic3.CHARTEVENTS`
WHERE ITEMID = 551 OR ITEMID = 552 OR ITEMID = 553 OR ITEMID = 224631
OR ITEMID = 224965 OR ITEMID = 224966
) AS t2
ON t1.ICUSTAY_ID = t2.ICUSTAY_ID
)
)
WHERE ITEMID IN (552, 553, 224965, 224966) AND pi_recorded <= 1440
)
SELECT ICUSTAY_ID #### Query error: Column name ICUSTAY_ID is ambiguous
FROM t
GROUP BY ICUSTAY_ID;
Both t1 and t2 have a column called ICUSTAY_ID. When you join them together into a single dataset you end up with 2 columns with the same name - which obviously can't work as there would be no way of uniquely identify each column.
You need to alias these columns in you code or not include one or the other if you don't need both

SQL - ROW_NUMBER that is used in a multi-condition LEFT JOIN

Two tables store different properties for each product: CTI_ROUTING_VIEW and ORD_MACH_OPS
They are both organized by SPEC_NO > MACH_SEQ_NO but the format of the Sequence number is different for each table so it can't be used for a JOIN. ORCH_MACH_OPS has MACHINE and PASS_NO, meaning if a product goes through the same machine twice, the row with the higher SEQ_NO will be PASS_NO 2, 3, etc. CTI_ROUTING_VIEW does not offer PASS_NO, but I can achieve the desired result with:
SELECT TOP (1000) [SPEC_NO]
,[SPEC_PART_NO]
,[MACH_NO]
,[MACH_SEQ_NO]
,[BLANK_WID]
,[BLANK_LEN]
,[NO_OUT_WID]
,[NO_OUT_LEN]
,[SU_MINUTES]
,[RUN_SPEED]
,[NO_COLORS]
,[PRINTDIEID]
,[CUTDIEID]
,ROW_NUMBER() OVER (PARTITION BY MACH_NO ORDER BY MACH_SEQ_NO) as PASS_NO
FROM [CREATIVE].[dbo].[CTI_ROUTING_VIEW]
I would think that I could use this artificial PASS_NO as a JOIN condition, but I can't seem to get it to come through. This is my first time using ROW_NUMBER() so I'm just wondering if I'm doing something wrong in the JOIN syntax.
SELECT rOrd.[SPEC_NO]
,rOrd.[MACH_SEQ_NO]
,rOrd.[WAS_REROUTED]
,rOrd.[NO_OUT]
,rOrd.[PART_COMP_FLG]
,rOrd.[SCHED_START]
,rOrd.[SCHED_STOP]
,rOrd.[MACH_REROUTE_FLG]
,rOrd.[MACH_DESCR]
,rOrd.REPLACED_MACH_NO
,rOrd.MACH_NO
,rOrd.PASS_NO
,rWip.MAX_TRX_DATETIME
,ISNULL(rWip.NET_FG_SUM*rOrd.NO_OUT,0) as NET_FG_SUM
,CASE
WHEN rCti.BLANK_WID IS NULL then 'N//A'
ELSE CONCAT(rCti.BLANK_WID, ' X ', rCti.BLANK_LEN)
END AS SIZE
,ISNULL(rCti.PRINTDIEID,'N//A') as PRINTDIEID
,ISNULL(rCti.CUTDIEID, 'N//A') as CUTDIEID
,rStyle.DESCR as STYLE
,ISNULL(rCti.NO_COLORS, 0) as NO_COLORS
,CAST(CONCAT(rOrd.ORDER_NO,'-',rOrd.ORDER_PART_NO) as varchar) as ORD_MACH_KEY
FROM [CREATIVE].[dbo].[ORD_MACH_OPS] as rOrd
LEFT JOIN (SELECT DISTINCT
[SPEC_NO]
,[SPEC_PART_NO]
,[MACH_NO]
,MACH_SEQ_NO
,[BLANK_WID]
,[BLANK_LEN]
,[NO_COLORS]
,[PRINTDIEID]
,[CUTDIEID]
,ROW_NUMBER() OVER (PARTITION BY MACH_NO ORDER BY MACH_SEQ_NO) as PASS_NO
FROM [CREATIVE].[dbo].[CTI_ROUTING_VIEW]) as rCti
ON rCti.SPEC_NO = rOrd.SPEC_NO
and rCti.MACH_NO =
CASE
WHEN rOrd.REPLACED_MACH_NO is null then rOrd.MACH_NO
ELSE rOrd.REPLACED_MACH_NO
END
and rCti.PASS_NO = rOrd.PASS_NO
LEFT JOIN INVENTORY_ITEM_TAB as rTab
ON rTab.SPEC_NO = rOrd.SPEC_NO
LEFT JOIN STYLE_DESCRIPTION as rStyle
ON rStyle.DESCR_CD = rTab.STYLE_CD
LEFT JOIN (
SELECT
JOB_NUMBER
,FORM_NO
,TRX_ORIG_MACH_NO
,PASS_NO
,SUM(GROSS_FG_QTY-WASTE_QTY) as NET_FG_SUM
,MAX(TRX_DATETIME) as MAX_TRX_DATETIME
FROM WIP_MACH_OPS
WHERE GROSS_FG_QTY <> 0
GROUP BY JOB_NUMBER, FORM_NO, TRX_ORIG_MACH_NO, PASS_NO) as rWip
ON rWip.JOB_NUMBER = rOrd.ORDER_NO
and rWip.FORM_NO = rOrd.ORDER_PART_NO
and rWip.TRX_ORIG_MACH_NO = rOrd.MACH_NO
and rWip.PASS_NO = rOrd.PASS_NO
WHERE rOrd.SCHED_START > DATEADD(DAY, -20, GETDATE())
I fixed it by adding a second partition.
ROW_NUMBER() OVER (PARTITION BY SPEC_NO, MACH_NO ORDER BY MACH_SEQ_NO) as PASS_NO

Return column1 only if column 2 contains all zeros

In my t-SQL db, I have an ItemLocation table. It lists warehouses, storage locations in the warehouses, items stored in those locations, and the current qty on hand. See below -
A warehouse (whse) can have multiple locations, and a location can have multiple items. As you can see from the image, there are items within locations that have '0' qty_on_hand.
What I would like to do is write a query that only returns locations that have absolutely NO qty_on_hand. For example, the highlighted location in my image (01-00-00A) would not be present in the result set of the executed query because it contains items that do have quantity. I'm only interested in the locations that don't have any quantity for any item whatsoever.
SELECT itemloc.*
FROM itemloc
WHERE itemloc.qty_on_hand = '0'
AND whse IN ('MW10','MW40','MW60')
ORDER BY whse, itemloc.loc
My query depicts qty_on_hand should = '0', but I don't want the qty_on_hand to equal '0', because then it will return every location that has an item with no inventory. I can't quite figure out what my query would look like for this situation.
Assuming the qty can only be 0 or positive value, you can use aggregation to find if max value for that location is 0.
select loc
from itemloc
group by loc
having max(qty) = 0
if it can be negative too, then use min as well:
select loc
from itemloc
group by loc
having max(qty) = 0 and min(qty) = 0
If you want to get the other columns as well you can use :
select *
from itemloc
where loc in (
select loc
from itemloc
group by loc
having max(qty) = 0
);
or window function:
select *
from (
select
i.*,
max(qty) over (partition by loc) max_qty
from itemloc i
) t where max_qty = 0;
You can create a subset of any whse/location combo that has qty_on_hand > 0 (for any item), and return the results not included in that subset.
SELECT a.*
FROM itemloc a
LEFT JOIN (select distinct whse,location from itemloc where qty_on_hand <> '0') b
ON a.whse = b.whse
AND a.location = b.location
WHERE b.whse IS NULL
SELECT *
FROM itemloc
WHERE
loc IN
(
SELECT loc
FROM itemloc
GROUP BY qty_on_hand
HAVING SUM(qty_on_hand) = '0'
)

compute Sum of Sum in sql

in SQL when I want to compute Sum of one column that is also Sum base on grouping, the total value is not correct.here I want to compute sum of Mand that is Sum(Qty) but the final result isn't correct.
Select Sum(Mand) from (Select TrackingFactor1 As Number ,SUM(Qty) As Mand from(
Select t.TrackingFactor1,SUM(
CASE
WHEN Direction = 1 THEN t.MajorUnitQuantity
WHEN Direction = 2 THEN -t.MajorUnitQuantity
ELSE 0
END
) AS Qty,
ROW_NUMBER() OVER(ORDER BY i.Date, i.VoucherCreationDate, v.InventoryVoucherID, i.InventoryVoucherItemID) AS
RowNumber
from LGS3.InventoryVoucher AS v
INNER JOIN LGS3.InventoryVoucherItem i ON v.InventoryVoucherID = I.InventoryVoucherRef
LEFT OUTER JOIN LGS3.InventoryVoucherItemTrackingFactor t ON i.InventoryVoucherItemID = t.InventoryVoucherItemRef
GROUP BY
v.InventoryVoucherID,
v.Number,
i.Date,
i.VoucherCreationDate,
i.InventoryVoucherItemID,
i.CounterpartEntityText,
t.TrackingFactor1 ,
v.FiscalYearRef
)As A
group by TrackingFactor1
Having SUM(Qty)>0) As AA

Teradata / Combine records with a UNION not working

I have a query with a UNION. I was trying to combine 2 records into 1. The top half gets records from 1 set of tables and the bottom half gets records from a differen set of tables. Both halves use fields from 2 derived queries. The results currently look like this:
Group Branch Ref NUm GL Amt Bank Amt
135 15 1z2x3c 25.00 0.00
135 15 1z2x3c 0.00 25.00
What I would like to see is this:
135 15 1z2x3c 25.00 25.00
I added the fields with 0.00 in each half so I had the same number of columns since the 2 halves bring back different amount fields. I have also compared all of the fields and their datatypes. If they were different, then I used CAST to make them the same. Can I do this with a UNION or is there some other method to combines 2 rows into 1? I really appreciate your help. Thanks.........
This is the sql I have developed:
with drvd_qry (operating_unit, grp_brn_id, ecr_dept_id, stn_id) as
(select
soh.operating_unit,
s.grp_brn_id,
s.ecr_dept_id,
s.stn_id
from stns s
inner join rfs.stn_ops_hierarchies soh on soh.stn_stn_id = s.stn_id
where substr(s.grp_brn_id, 1, 2) = 'G1'
group by soh.operating_unit, s.grp_brn_id, s.ecr_dept_id, s.stn_id),
qry_drvd (department, ecr_ticket_no, open_item_id, rnt_agr_nbr, monetary_amount) as
(select
j.department,
j.ecr_ticket_no,
j.open_item_id,
j.rnt_agr_nbr,
cast(j.monetary_amount as decimal (15,2))
from
rfs.journal_entries j
where
j.business_unit = 'A0141'
and j.accounting_date = cast ('23-SEP-2015' as date format 'dd-MMM-YYYY')
and j.account_gl = '109850')
select
bb.BU,
bb.GPBR,
bb.STN_ID,
bb.DEPTID,
cast(ft.mrchnt_nbr as decimal (20,0)) as MERCH_NUM,
bb.TICKET_NUM,
ft.prim_acct_frst_six_dgt_nbr as FIRST6,
ft.prim_acct_last_four_dgt_nbr as LAST4,
bb.AUTH_NUM,
cast(ft.stlmt_uniq_ref_nbr as decimal (20,0)) as REF_NUM,
bb.GL_AMT,
bb.BANK_AMT
from
(select
aa.bu,
aa.gpbr,
aa.stn_id,
aa.deptid,
aa.ticket_num,
p.auth_nbr as AUTH_NUM,
p.fin_tran_ref_id,
aa.GL_AMT,
CAST(0 AS DECIMAL (15,2)) as BANK_AMT
from
(select
dq.operating_unit as BU,
dq.grp_brn_id as GPBR,
dq.stn_id as STN_ID,
qd.department as DEPTID,
qd.ecr_ticket_no as TICKET_NUM,
qd.open_item_id,
qd.rnt_agr_nbr,
cast(qd.monetary_amount as decimal (15,2)) as GL_AMT
from
qry_drvd qd,
drvd_qry dq
where dq.ecr_dept_id = qd.department ) aa
left outer join rfs.pymts p on p.ecr_pymt_id = cast(aa.open_item_id as decimal(19,0))
and p.ram_rea_rnt_agr_nbr = aa.rnt_agr_nbr) bb
left outer join paymt.fin_tran ft on ft.fin_tran_ref_id = bb.fin_tran_ref_id
UNION
select
b.BU,
b.GPBR,
b.STN_ID,
b.DEPTID,
cast(b.MERCH_NUM as decimal(20,0)),
qd.ecr_ticket_no as TICKET_NUM,
b.FIRST6,
b.LAST4,
b.AUTH_NUM,
cast(b.REF_NUM as decimal(20,0)),
b.GL_AMT,
b.BANK_AMT
from
(select
a.BU,
a.GPBR,
a.STN_ID,
a.DEPTID,
a.MERCH_NUM,
a.REF_NUM,
a.FIRST6,
a.LAST4,
p.auth_nbr as AUTH_NUM,
p.ecr_pymt_id,
a.GL_AMT,
a.BANK_AMT
from
(select
dq.operating_unit as BU,
dq.grp_brn_id as GPBR,
dq.stn_id as STN_ID,
dq.ecr_dept_id as DEPTID,
cast(f.merch_num as varchar(20)) as MERCH_NUM,
f.ret_ref_num as REF_NUM,
ft.prim_acct_frst_six_dgt_nbr as FIRST6,
ft.prim_acct_last_four_dgt_nbr as LAST4,
CAST(0 AS DECIMAL(15,2)) as GL_AMT,
cast(case when f.tran_typ_cde = 1 then f.tran_amt
when f.tran_typ_cde = 4 then f.tran_amt * -1
end as decimal (15,2)) as BANK_AMT,
ft.fin_tran_ref_id
from paymt.fndng_recncl_dtl_rprt f,
rfs.cc_mrchnt_nbr m,
drvd_qry dq,
paymt.fin_tran ft
--rfs.pymts p
where f.row_stat_cde = 'A'
and cast (f.tran_proc_date as date format 'MM/DD/YYYY') = '09/23/2015'
and m.mrchnt_nbr = f.merch_num
and m.credit_card_typ = 'VI'
and dq.stn_id = m.sta_stn_id
and ft.stlmt_uniq_ref_nbr = f.ret_ref_num
group by
dq.operating_unit,
dq.grp_brn_id,
dq.stn_id,
dq.ecr_dept_id ,
f.merch_num,
f.ret_ref_num,
ft.prim_acct_frst_six_dgt_nbr,
ft.prim_acct_last_four_dgt_nbr,
GL_AMT,
BANK_AMT,
ft.fin_tran_ref_id) a
left outer join rfs.pymts p on p.fin_tran_ref_id = a.fin_tran_ref_id) b
left outer join qry_drvd qd on cast(qd.open_item_id as decimal(19,0)) = b.ecr_pymt_id
Perform the union and then use group by and because you dummy fields are 0 use SUM to join both rows
SELECT "Group", "Branch", "Ref Num", SUM("GL Amt"), SUM("Bank Amt")
FROM (
SELECT * FROM YourQuery1
UNION ALL
SELECT * FROM YourQuery2
) as t
GROUP BY
"Group", "Branch", "Ref Num"
Since data is coming from two different tables and then I believe doing group by over the union will not help as derived table using with clause cannot be used inside subquery .If possible load this data to a a volatile table and then do group by and find the max of ("GL Amt"), ("Bank Amt") and or create a view and then query...