I need to know the total number of Jobs completed by each Employee as well as the total Rate if I only have the following information.
One job can be completed by 2 different Employees.
For example, Employee A has completed 2 jobs (JobID and JobID 2). So the total segments of Employee A is 30 segments but per jobID is different segment rate.
But I just need the total rate of all segments. SO Employee A has complete 2 jobs and a total of 90USD
(10 x 5 USD) + (20 x 2 USD) = 90 USD
This is what I have so far:
select
EmployeeID, count(distinct JobID)
from
Table_name
group by
EmployeeID
But I do not know how to compute the total rate per employee.
Image of the table:
This will help you:
select EmployeeID, COUNT(distinct JobID) as [Total Jobs], SUM([Segements per Job] * [Rate per Segement (USD)]) as [Total Rate (USD)]
from Table_name
Group by EmployeeID
SUM([Segements per Job] * [Rate per Segement (USD)]) will multiply the segements and rate and then sum them for each employee as the query is grouped based on EmployeeID.
Related
I have a table that contains Transactions of Customers.
I should Find Customers That had have at least 2 transaction with amount>20000 in Three consecutive days each month.
For example , Today is 2022/03/12 , I should Gather Data Of Transactions From 2022/02/13 To 2022/03/12, Then check These Data and See If a Customer had at least 2 Transaction With Amount>=20000 in Three consecutive days.
For Example, Consider Below Table:
Id
CustomerId
Transactiondate
Amount
1
1
2022-01-01
50000
2
2
2022_02_01
20000
3
3
2022_03_05
30000
4
3
2022_03_07
40000
5
2
2022_03_07
20000
6
4
2022_03_07
30000
7
4
2022_03_07
30000
The Out Put Should be : CustomerId =3 and CustomerId=4
I write query that Find Customer For Special day , but i don't know how to find these customers in one month with out using loop.
the query for special day is:
With cte (select customerid, amount, TransactionDate,Dateadd(day,-2,TransactionDate) as PrevDate
From Transaction
Where TransactionDate=2022-03-12)
Select CustomerId,Count(*)
From Cte
Where
TransactionDate>=Prevdate and TransactionDate<=TransactionDate
And Amount>=20000
Group By CustomerId
Having count(*)>=2
Hi there are many options how to achieve this.
I think that easies (from perfomance maybe not) is using LAG function:
WITH lagged_days AS (
SELECT
ISNULL(LAG(Transactiondate) OVER(PARTITION BY CustomerID ORDER BY id),
LEAD(Transactiondate) OVER(PARTITION BY CustomerID ORDER BY id)) lagged_dt
,*
FROM Transaction
), valid_cust_base as (
SELECT
*
FROM lagged_days
WHERE DATEPART(MONTH, lagged) = DATEPART(MONTH, Transactiondate)
AND datediff(day, Transactiondate, lagged_dt) <= 3
AND Amount >= 20000
)
SELECT
CustomerID
FROM valid_cust_base
GROUP BY CustomerID
HAVING COUNT(*) >= 2
First I have created lagged TransactionDate over customer (I assume that id is incremental). Then I have Selected only transactions within one month, with amount >= 20000 and where date difference between transaction is less then 4 days. Then just select customers who had more than 1 transaction.
In LAG First value is always missing per Customer missing, but you still need to be able say: 1st and 2nd transaction are within 3 days. Thats why I am replacing first NULL value with LEAD. It doesn't matter if you use:
ISNULL(LAG(Transactiondate) OVER(PARTITION BY CustomerID ORDER BY id),
LEAD(Transactiondate) OVER(PARTITION BY CustomerID ORDER BY id)) lagged_dt
OR
ISNULL(LEAD(Transactiondate) OVER(PARTITION BY CustomerID ORDER BY id),
LAG(Transactiondate) OVER(PARTITION BY CustomerID ORDER BY id)) lagged_dt
The main goal is to have for each transaction closest TransactionDate.
I’m having trouble figuring out how to calculate the daily compound interest for an initial amount, over various rates periods, producing a new total that includes the interest amounts from each rate period. The challenge is that for each subsequent rate period you have to calculate the interest on the amount plus the previous interest!!! So it’s not a simple running total.
For example, using the following rates table.
rate from date rate to date rate
-------------- ------------ ----
2013-07-15 2013-09-30 3
2013-10-01 2013-12-31 4
2014-01-01 2014-03-31 3
Using an initial amount of $32,550.37, I have to traverse each rate period with an interest calculation, producing the final amount of $33,337.34.
rate from date rate to date rate daysx amount interest
-------------- ------------ ---- ----- ---------- --------
2013-07-15 2013-09-30 .03 78 32,550.37 209.34
2013-10-01 2013-12-31 .04 92 32,759.71 331.94
2014-01-01 2014-03-31 .03 90 33,091.65 245.69
Final Amount 33,337.34
For example, the initial amount of $32,550.37 has interest of $209.34 at 3%. For the second rate period, I add that interest to the amount, which is $32,759.71 and then calculate the interest on $32,759.71 at 4%. Etc.
I’m using Netezza which does not allow recursive SQL, so I have been trying to use windowed functions, but not with any success yet …
DROP TABLE TRATES;
CREATE TABLE TRATES (RATE_FROM_DATE DATE, RATE_TO_DATE DATE, RATE DECIMAL(10,2));
INSERT INTO TRATES VALUES ('2013-07-15','2013-09-30',.03);
INSERT INTO TRATES VALUES ('2013-10-01','2013-12-31',.04);
INSERT INTO TRATES VALUES ('2014-01-01','2014-03-31',.03);
SELECT TRATES.*
, DAYS_BETWEEN(RATE_FROM_DATE, RATE_TO_DATE)+1 AS DAYSX
, (AMOUNT * POW(1+(RATE)/365,(DAYS_BETWEEN(RATE_FROM_DATE, RATE_TO_DATE)+1)))) – AMOUNT
AS INTEREST
, FIRST_VALUE(AMOUNT) OVER(ORDER BY RATE_FROM_DATE)
*(POW(1+(RATE/100)/365,(DAYS_BETWEEN(RATE_FROM_DATE, RATE_TO_DATE)+1)))
AS NEW_AMOUNT
FROM TRATES
JOIN (SELECT 32550.37 AS AMOUNT) AS TPARMS ON 1=1
;
Any help would be greatly appreciated.
I’m using the fact that the interest rate is shifting is not dependent on which order the shifts occur, so 3 days at 3% followed but 4 days at 2% gives the same result as 4 days at 2% followed by 3 days at 3%.
Furthermore summing logarithms will allow you to multiply over rows:
https://blog.jooq.org/2018/09/21/how-to-write-a-multiplication-aggregate-function-in-sql/
In short: log(a1)+log(a2)+..+log(an) = log(a1*a2*..*an)
This is pretty close to a useful solution (and performs reasonably):
DROP TABLE TRATES if exists;
CREATE temp TABLE TRATES (RATE_FROM_DATE DATE, RATE_TO_DATE DATE, RATE DECIMAL(10,2));
INSERT INTO TRATES VALUES ('2013-07-15','2013-09-30',.03);
INSERT INTO TRATES VALUES ('2013-10-01','2013-12-31',.04);
INSERT INTO TRATES VALUES ('2014-01-01','2014-03-31',.03);
create temp table dates as
select '2010-01-01'::date -1+row_number() over (order by null) as Date
from ( select * from
_v_dual_dslice a cross join _v_dual_dslice b cross join _v_dual_dslice c cross join _v_dual_dslice d
limit 10000 ) x
;
SELECT AMOUNT*pow(10,sum(log(1+rate::double/365)))
FROM TRATES join dates
on date between RATE_FROM_DATE and RATE_TO_DATE
JOIN (SELECT 32550.37 AS AMOUNT) AS TPARMS ON 1=1
group by AMOUNT
I'm sure you can make it prettier with a bit of effort and even let it return the results on select days in the 260 day interval if needed
I want to be able to find out the monthly average of a count
My code at the moment is
SELECT
company,
COUNT(company) AS 'count'
FROM Information
GROUP BY company
I basically need it to be
SELECT company,
count(company) as 'count'
avg(count(company)) per month as 'average'
FROM Information
group by company
I want the result to look something like this
company count monthly average
a 5 6
b 13 14
c 2 2
d 45 45
e 23 21
f 6 5
A very simple approach would be to count per company and month first and then aggregate this data to get total and avarage per company.
select
company,
sum(cnt) as records,
avg(cnt) as records_per_month
from
(
select company, year(start_date), month(start_date), count(*) as cnt
from information
group by company, year(start_date), month(start_date)
) agg
group by company;
But read my comment to your question.
SELECT YEAR(yourDate) * 100 + MONTH(yourDate) YYMM,
company,
count(company) as 'count'
avg(count(company)) per month as 'average'
FROM Information
group by company
,YEAR(yourDate) * 100 + MONTH(yourDate)
I am trying to find the difference of expenses of previous and current month in sql.
I have a table like this
Date Amount Category
2/18/2015 100 Salary
2/12/2015 150 Rent
2/21/2015 200 Allowances
1/4/2015 200 Salary
1/17/2015 50 Rent
1/20/2015 100 Allowances
Now I want a result like this
Category CurrentMonthAmount PreviousMonthAmount Difference
Salary 100 200 100
Rent 150 50 100
Allowances 200 100 100
Try using conditional Aggregate
;WITH cte
AS (SELECT Category,
Max(CASE WHEN Month([date]) = Month(Getdate()) and year([date]) =year(getdate()) THEN amount END) CurrentMonthAmount,
Max(CASE WHEN Month([date]) = Month(Getdate()) - 1 and year([date]) =year(getdate()) THEN amount END) PreviousMonthAmount
FROM Yourtable
GROUP BY Category)
SELECT Category,
CurrentMonthAmount,
PreviousMonthAmount,
[Difference]=Abs(CurrentMonthAmount - PreviousMonthAmount)
FROM cte
SQLFIDDLE DEMO
Are you trying to do the computations within your SQL only or via some scripts like PHP.? Furthermore, can you state if you are choosing specific records for this operation (specific rows i mean). Give some more clarification
I am trying to write a join query but can't seem to filter it out. I'm selecting an invoice table and and applied payments table. I want to get the balance of all invoice totals amount - applied amounts. I can get the applied amounts fine using sum but when I try to get the total invoice amount, it is too high because its pulling multiple invoice results if more than one payment has been applied to it.
My results:
Invoice No | Amount | Paid
----------------------------
1 | 10 | 5
1 | 10 | 2
2 | 50 | 50
How do I select the sum invoice amount for unique invoice numbers?.
Query Overview:
Select sum(invoiceamount) - sum(appliedamount) as balance
FROM invoice
LEFT JOIN invoicepayments ON invoice.invoiceid = invoicepayments.invoiceid
You're actually looking for a very simple use of GROUP BY. You want to group every result that is the same Invoice/Amount, and then subtract the total (SUM) of the Paid column for that group from the Amount you are grouping on.
SELECT SUM(balance) FROM
(
SELECT invoiceamount - SUM(appliedamount) as balance
FROM invoice
GROUP BY invoiceid, invoiceamount
) balances
You can do it with CTE where you first calculate amount paid on each invoice and than join it to invoices to figure out what is left to pay for each invoice.
;WITH InvoicePay
AS (
SELECT invoiceid
,SUM(appliedamount) AS totalpaid
FROM invoicepayments
GROUP BY invoiceid
)
SELECT i.invoiceID
,i.invoiceamount - totalpaid as Balance
FROM Invoice AS i
JOIN InvoicePay AS ip
ON i.invoiceid = ip.invoiceid