unpivot calculated columns value - sql

SELECT
P.EmployeeId,
(P.Amount*1)*T.RegularHours as RegularEarnings
,(P.Amount*1.5)*T.OTHours as OvertimeEarnings
,(P.Amount*2)*T.DOTHours as DoubleOvertimeEarnings
,((P.Amount*1)*T.RegularHours)+((P.Amount*1.5)*T.OTHours )+((P.Amount*2)*T.DOTHours)+((SELECT ISNULL(SUM(AMOUNT),0) FROM EmployeeEarning WHERE EmployeeId=T.EmployeeId)) as GrossPay
FROM TimeSheet as T
INNER JOIN PayInformation as P ON T.EmployeeId=P.EmployeeId
above is my select statement which returns me earnings in column format . I want to unpivot my resulted table so that each employeeId have two columns one is earning type and second one is amount of earning .
I already done with simple unpivote
select unpvt.car_id, unpvt.attribute, unpvt.value
from #cars c
unpivot (
value
for attribute in (Make, Model, Color)
) unpvt
but now stuck as i have to unpivot tables values calculated in select statement .
I have attempt something more and here is my latest code
SELECT unpvt.EmployeeId, unpvt.Earning, unpvt.Amount
FROM
(SELECT
P.EmployeeId,
(P.Amount*1)*T.RegularHours as RegularEarnings
,(P.Amount*1.5)*T.OTHours as OvertimeEarnings
,(P.Amount*2)*T.DOTHours as DoubleOvertimeEarnings
,((P.Amount*1)*T.RegularHours)+((P.Amount*1.5)*T.OTHours )+((P.Amount*2)*T.DOTHours)+((SELECT ISNULL(SUM(AMOUNT),0) FROM EmployeeEarning WHERE EmployeeId=T.EmployeeId)) as GrossPay
FROM TimeSheet as T
INNER JOIN PayInformation as P ON T.EmployeeId=P.EmployeeId )as c
unpivot (
Amount
for Earning in (RegularEarnings,OvertimeEarnings,DoubleOvertimeEarnings)
)unpvt
and now i am getting error
The type of column "OvertimeEarnings" conflicts with the type of other columns specified in the UNPIVOT list.

Related

How to use unpivot operator to combine rows and columns?

I need to group customers by GroupName. Customers can be duplicated on each GroupName. Each GroupName has a unique number called "GroupCode" in table OCQG. Customer table (OCRD) has separate column for Each GroupCode. As an example, C-0001 customer can have more group names.We can identify GroupCodes for each customer by see Group1,...,Group64 column values.(If this value = Y).Table structure as follows.Please help me.
I tried following query.But it didn't work.
SELECT p.CardCode, REPLACE(p.QryGroup,'GROUP','') groupcode, ocqg.GroupName
FROM ocrd UNPIVOT
( value
FOR groupcode IN ([QryGroup1],[QryGroup2],[QryGroup3])
) as p,
ocqg
WHERE value = 'Y' and
ocqg.GroupCode = REPLACE(p.groupcode,'GROUP','')
order by p.CardCode
Table Structure as follows,
I recommend using APPLY for this purpose:
SELECT ocrd.CardCode, v.groupcode, ocqg.GroupName
FROM ocrd CROSS APPLY
(VALUES (1, QryGroup1),
(2, QryGroup2),
(3, QryGroup3),
. . .
) v(GroupCode, Value) JOIN
ocqg
ON ocqg.GroupCode = v.GroupCode
WHERE v.value = 'Y'
ORDER BY p.CardCode;
UNPIVOT is bespoke syntax for SQL Server and Oracle that does one thing.
On the other hand, APPLY implements "lateral join"s.' These are very powerful -- much more powerful than UNPIVOT -- and supported by more databases.

Column l' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause - but it is

I have a sql subquery that does the following - it calculates some sums based on a over partition of a column. After that in I want to inner join the table with itself so that I could get the difference between dates.
The problem that it is showing is:
Column 'tblFinansijskiPodaci.DatumVal' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
The problem started when I inserted the date values in the DATEDIFF. When I insert some random date values like '2017/08/25', '2011/08/25' it works fine.
Is maybe my join in the wrong place?
This is my query:
SELECT P2.FinID, P2.Firma, P2.BrojDok, P2.DatumVal,P2.Saldo ,P2.SaldoTotal2,
IIF(P2.SaldoTotal2<0,0,IIF(P2.SaldoTotal2<1,(DATEDIFF(DAY,P2.DatumVal, b.DatumVal)),0))
AS NumberOfDays
FROM
(
SELECT P1.FinID, P1.Firma,P1.BrojDok,P1.DatumVal,P1.Saldo,P1.SaldoTotal,
IIF(P1.SaldoTotal<0,0,IIF(P1.SaldoTotal>1,1,0)) AS SaldoTotal1,
IIF(P1.SaldoTotal<0,0,IIF(P1.SaldoTotal<1,0,1)) AS SaldoTotal2
FROM
(
SELECT P.FinID,P.Firma,P.BrojDok,P.DatumVal,P.Saldo ,
SUM(Saldo) OVER (PARTITION BY BrojDok ORDER BY FinID) AS SaldoTotal
FROM
(
SELECT a.FinID, a.Firma, a.Konto,a.NazivKonta, a.NazFirme, a.BrojDok,
a.DatumVal,a.Valuta,
Sum(IIf(a.[Konto] Like '2%',a.[Duguje] -a.[Potrazuje],a.[Potrazuje] -a.[Duguje]))
AS Saldo
FROM tblFinansijskiPodaci a WHERE a.Firma = 1 AND a.Konto = 2040
AND a.Partner = 1137
GROUP BY a.FinID,a.Firma,a.NazFirme,a.Konto,a.NazivKonta,a.BrojDok,
a.DatumVal,a.Valuta,a.Duguje,a.Potrazuje
) AS P
GROUP BY FinID,Firma,BrojDok,Saldo,DatumVal
) AS P1
GROUP BY P1.FinID,P1.Firma,P1.BrojDok,P1.DatumVal,P1.Saldo,P1.SaldoTotal
) AS P2
INNER JOIN tblFinansijskiPodaci b ON b.BrojDok=P2.BrojDok
GROUP BY P2.FinID,P2.Firma,P2.BrojDok,P2.Saldo,P2.SaldoTotal,P2.SaldoTotal1,P2.SaldoTotal2,P2.DatumVal
ORDER BY BrojDok
Try to add b.DatumVal in your last GROUP BY clause.

Access Query subtract 2 different column from different row in same table with same ID

I have a table deposit which have column Refund_amt ,Deposit_amt having different Rows with same GR_no . here my question is ,I want to subtract deposit_amt column from Refund_amt
I tried various alternative in query but didn't succeed
My query :
SELECT d.Gr_no
, d.Rec_No
, d.Deposite_Amt
, d.penalty_Amt
, d.Refund_Amt - Refund
, s.Name
, s.cur_std
, cur_div
From
( select d.Refund_Amt refund
from deposite d
, std_gr s
where d.Gr_no = s.Gr_no )
Result would look like this in final total column :
Thank you
You are looking for an aggregation per std_gr: the sum of the deposites minus the sum of the refunds. One way is to do this aggregation in a subquery and join this subquery to your table.
select
d.*, sums.final_total
from deposite d
join
(
select std_gr, nz(sum(deposite_amt),0) - nz(sum(refund_amt),0) as final_total
from deposite
group by std_gr
) as sums on sums.std_gr = d.std_gr
order by d.rec_no;

Select number of records until the sum is less than 'n' - Access SQL

I am working on Microsoft Access. My requirement is, User will give any percentage value and I have to find the number of IDs which form the percentage of the 'Value' column. For e.g. in the below DataSet (it is sorted by descending of value column which is also required), the sum of all values is '8409131'.
ID NAME VALUE
1000000090 A 2295175
1000000974 B 1942753
1000015555 C 1887965
1000004864 D 1310400
1000015557 E 972838
If I enter 75%, the value is 65170765.25, so I need to return all the IDs which forms the '65170765', less than or equals to. So in this case below are the sum of values which are less than 65170765.
ID NAME VALUE
1000000090 A 2295175
1000000974 B 1942753
1000015555 C 1887965
Is this possible to achieve my requirement in Access SQL?
My plan is to make a running total column to find sum of first two rows and then sum of that value with next row. But in Access, I am not able to figure out how to create incremental rows in select query also to achieve this.
Query I tried:
SELECT T1.ID, T1.NAME, T1.VALUE,(T1.VALUE + T2.VALUE)
FROM (
SELECT ID , RUN_MANAGER.NAME AS NAME, RUN_MANAGER.REPORTING_PERIOD, SUM(VALUE) As VALUE
FROM DATA
INNER JOIN RUN_MANAGER
ON DATA.RUN_NUMBER=RUN_MANAGER.RUN_NUMBER
WHERE RUN_MANAGER.NAME='A'
GROUP BY ID,RUN_MANAGER.NAME
ORDER BY SUM(VALUE) DESC) AS T1
INNER JOIN (
SELECT ID , RUN_MANAGER.NAME AS NAME, RUN_MANAGER.REPORTING_PERIOD, SUM(VALUE) As VALUE
FROM DATA
INNER JOIN RUN_MANAGER
ON DATA.RUN_NUMBER=RUN_MANAGER.RUN_NUMBER
WHERE RUN_MANAGER.NAME='A'
GROUP BY ID,RUN_MANAGER.NAME
ORDER BY SUM(VALUE) DESC) AS T2
ON T1.ID=T2.ID+1
This is not a duplicate question. The problem is, this question is based on Access SQL and also I do not have any incremental ascending rows.
If you have a table like t:
ID NAME VALUE
1000000090 A 2295175
1000000974 B 1942753
1000015555 C 1887965
1000004864 D 1310400
1000015557 E 972838
You can use this query:
SELECT *
FROM t
WHERE
(SELECT SUM(VALUE) FROM t ti WHERE ti.Name <= t.Name) < (SELECT SUM(VALUE) FROM t ti) * 0.75
For this:
ID NAME VALUE
1000000090 A 2295175
1000000974 B 1942753
1000004864 D 1310400

How to pass value to and join correlated query having WITH clause?

I need to pass from one select value to another one to get the calculation done and join the results but having problem with this "with" clause sub query.
This one calculates balance from supplied number loan_id from the second query
WITH my_select (balance, type) As
(
select sum(amount_o-amount_h) as balance, type
from decret d
where d.idnumber = **loan_id**
and d.DATE_D <= '2013-10-31'
and type in (1,2,3,4,11,12,13,18,20,25)
group by type
having sum(amount_o-amount_h) <> 0
)
select sum(balance) FROM my_select //just returns client balance
And this one selects clients data and I want for every client add the balance also to the result calculated in first query.
SELECT *, /*balance*/ from clients
where **loan_id** in (select LoanNum
from NumsFromEx)
How to join them together? (I have simplified a little bit queries to show it cleaner)
Given the sample queries, the following should work:
WITH cteBalances AS
(
SELECT loan_id, SUM(amount_o-amount_h) AS balance
FROM decret d
WHERE d.DATE_D <= '2013-10-31'
AND type IN (1,2,3,4,11,12,13,18,20,25)
GROUP BY loan_id
)
SELECT c.*, b.balance
FROM clients c
LEFT JOIN cteBalances b ON b.loan_id = c.loan_id
WHERE loan_id IN (SELECT LoanNum
FROM NumsFromEx)