I created a table called 'donation'.
This table has
supporter_KEY ( member unique identifier)
first_name,
last_name,
donation_key (transaction unique identifier)
email
amount and date
Here is some data
supporter_KEY first_name last_name email donation_key (date) (amount)
37519405 ALEX LANGER alex#email.com 12447199 2011-04-14 10:38:00.000 100
37519483 Anthony Russo anthony#smail3.com 12464169 2012-07-30 14:12:00.000 125
37519656 Bert Kaplan sample1#aol.com 12460672 2011-11-25 08:08:00.000 35
37519905 Brett Graham sample2#yahoo.com 12466260 2013-01-14 10:43:00.000 100
37519939 Bruce Decker sample3#hotmail.com 12466441 2013-03-20 08:59:00.000 25
37520331 Craig Pettigrew sample4#aol.com 12464780 2012-08-28 13:52:00.000 25
37520787 Donn Schaible sample9#aol.com 12466886 2013-04-09 16:50:00.000 125
37521145 George Cooper sample43#gmail.com 12420119 2011-03-09 10:17:00.000 100
37521145 George Cooper sample43#gmail.com 12459908 2011-07-19 09:19:00.000 50
I am trying in one query to pull the latest transaction amount and date and in the other query to pull the first transaction date and amount
Here is each query:
Query for first transaction date and amount:
SELECT supporter_KEY,
first_name,
last_name,
email,
donation_key,
MIN(date) as first_transaction_date,
MIN(Amount) as first_transaction_amount
FROM donation
WHERE supporter_KEY > '1'
GROUP BY supporter_KEY,first_name,last_name,email,donation_key
And the Query for the latest transaction date and amount:
SELECT supporter_KEY ,
first_name ,
last_name,
email,
donation_key ,
MAX(date) as latest_transaction_date,
MAX(Amount) as latest_transaction_amount
WHERE supporter_KEY > '1'
FROM donation
GROUP BY supporter_KEY,first_name,last_name,email,donation_key
I just want to make sure I am on the right track and I would also like to pull the largest Trx Date & Amount (?).
Can someone help me out?
The queries are essentially the same. Here's the query for the first transaction, to get the latest transaction change the MIN in the subquery to MAX. Note that this will only select the first row (with unknown sorting) if there is more than one row with the same date.
SELECT TOP 1
supporter_KEY,
first_name,
last_name,
email,
donation_key,
date as first_transaction_date,
amount as first_transaction_amount
FROM
donation
WHERE
date = (SELECT MIN(date) FROM donation)
Related
Let's say I have a table
CustId Name Age Gender Business Code
1 John 24 Male Automobiles 1
2 Peter 30 Male Space 3
2 Peter 30 Male IT null
3 Kris 48 Female Infra null
I need output as follows
CustId Name Age Gender Business Code
1 John 24 Male Automobiles 1
2 Peter 30 Male Space 3
3 Kris 48 Female CodeNotAvailable null
Peter has two businesses one with code and another without code. So, the row without code is removed.
Kris has business without code, so need to display CodeNotAvailable in Business column.
We can use ROW_NUMBER() to get the row numbers and pick the row. By default, SQL Server orders NULL first. We need to use order by code desc to get the non-null value as the first row in the ROW_NUBER()
SELECT CustId,Name, Age, Gender, Business, Code
from
(
SELECT *, ROW_NUMBER() OVER(PARTITION BY CustId ORDER BY Code desc) as rnk
FROM Table) as t
WHERE rnk = 1
;with r as (
select Custid, Name, Age, Gender,
case when code is null then 'CodeNotAvailable' else Business end as Business,
Code
from myTab
)
select max(CustId) CustId, Name, Age, Gender, Business, Code
from r
group by Name, Age, Gender, Business, Code
i have employees data in my database, if i insert the employee data it will automatically calculate the age that i written in stored procedure, but if the date of birth of an employee may be tomorrow if i retrieve the employee details will it automatically show the updated one
Code:
Declare #age float
set #age=(select DATEDIFF(YYYY,#DATE_OF_BIRTH,
GETDATE())) update Employee_details set AGE=#AGE where
BADGE_NO=#BADGE_NO
With SQL Server, if you store the date of birth, you can add the age as a computed column:
CREATE TABLE employees (id INT, name VARCHAR(25), dob DATE,
age AS (CONVERT(INT,CONVERT(CHAR(8),GETDATE(),112))-CONVERT(CHAR(8),dob,112))/10000)
INSERT INTO employees (id, name, dob) VALUES (1, 'Max Smith', '12/31/1983')
INSERT INTO employees (id, name, dob) VALUES (1, 'Scott Smith', '2/8/1982')
INSERT INTO employees (id, name, dob) VALUES (1, 'Carolyn Smith', '11/1/1985')
Note the age column declaration - and thanks cars10m for providing this calculation! - which accurately gives you age based on a date-of-birth column and the current date:
age AS (CONVERT(INT,CONVERT(CHAR(8),GETDATE(),112))-CONVERT(CHAR(8),dob,112))/10000)
select * from employees gives you (as of today, 8/9/2017):
id name dob age
1 Max Smith 1983-12-31 33
1 Scott Smith 1982-02-08 35
1 Carolyn Smith 1985-11-01 31
Use a computed column!
I need to write a DAX statement which is somewhat complex from a conceptual/logical standpoint- so this might be hard to explain.
I have two tables.
On the first table (shown below) I have a list of numeric values (Wages). For each value I have a corresponding date range. I also have EmployeeID and FunctionID. The purpose of this table is to keep track of the hourly Wages paid to employees performing specific functions during specific date ranges. Each Function has it's own Wage on the Wage table, BUT each employee might get paid a different Wage for the same Function ( there is also a dimension for functions and employees ).
'Wages'
Wage StartDate EndDate EmployeeID FunctionID
20 1/1/2016 1/30/2016 3456 20
15 1/15/2016 2/12/2016 3456 22
27.5 1/20/2016 2/20/2016 7890 20
20 1/21/2016 2/10/2016 1234 19
On 'Table 2' I have a record for every day that an Employee worked a certain Function. Remember, Table 1 contains the Wage information for every function.
'Table 2'
Date EmployeeID FunctionID DailyWage
1/1/2016 1234 $20 =CALCULATE( SUMX( ??? ) )
1/2/2016 1234 $20 =CALCULATE( SUMX( ??? ) )
1/3/2016 1234 $22 see below
1/4/2016 1234 $22
1/1/2016 4567 $27
1/2/2016 4567 $27
1/3/2016 4567 $27
(Note that wages can change over time)
What I'm trying to do is create a Calculated Column on 'Table 2' called 'DailyWage'. I want every row on 'Table 2' to tell me how much the EmployeeID was paid for the full day (assuming an 8 hour workday).
I'm really struggling with the logic steps, so I'm not sure what the best way to do this calculation is...
To make things worse, an EmployeeID might get paid a different Wage for the same Function on a different Date. They might start out at one wage working function X and then generally, their wage should go up a few months in the future... That means that if I try to concatenate the EmployeeID and the FunctionID, I won't be able to connect the tables on the concatenated value because neither table will have unique values.
So in other words, if we CONCATENATE the EmployeeID and FunctionID into EmpFunID, we need to take the EmpFunID + the date for the current row and then say "take the EmpFunID in the current row, plus the date for the current row and then return the value from the Wage column on the Wages table that has the same EmpFunID AND has a StartDate less that the CurrentRowDate AND has an EndDate greater than the CurrentRowDate
HERE IS WHAT I HAVE SO FAR:
Step 1 = Filter 'Wages' table so that StartDate < CurrentRowDate
Step 2 = Filter 'Wages' table so that EndDate > CurrentRowDate
Step 3 = LOOKUPVALUE( 'Wages'[Wage], 'Wages'[EmpFunID], Table2[EmpFunID])
Now I just need that converted into a DAX function.
Not sure if got it totally right, but maybe something similar? If you put this into Table2 as a calculated column, it will transform the current row context of the Table2 into a filter context.
So SUMX will use the current row's data from Table2, and will do a sum on a filtered version of the wages table: wages table will be filtered by using the current date, employeeid and functionid from Table2, and for each row in the Table2 itt will only sum those wages, which are belong to the current row.
CALCULATE(
SUMX(
FILTER(
'Wages',
'Wages'[StartDate] >= 'Table2'[Date],
'Wages'[EndDate] <= 'Table2'[Date],
'Wages'[EmployeeId] = 'Table2'[EmployeeId],
'Wages'[FunctionId] = 'Table2'[FunctionId]
),
'Wages'[Wage]
)
I've got a table in SQL Server with several columns. The relevant ones are:
name
distance
create_date
I have many people identified by name, and every few days they travel a certain distance. For example:
name distance create_date
john 15 09/12/2014
john 20 09/22/2014
alex 10 08/15/2014
alex 12 09/05/2014
john 8 09/30/2014
alex 30 09/12/2014
What i would like is a query that for each person returns the sum of distance between two dates, and the create_date of the last entry during that date range, ordered by highest distance DESC. For example, given a date range of 08/01/2014 to 09/25/2014 I would expect this:
name distance create_date
alex 52 09/12/2014
john 35 09/22/2014
I thought of trying to do this with a SUM query with a sub query to get the newest date in the range but I think this is not efficient.
Does someone have an idea for this?
Thank you!
SELECT name,
SUM(distance) AS distance,
MAX(create_date) AS create_date
FROM Table
WHERE create_date >= '20140801' AND create_date < '20140925'
GROUP BY name
SQL Fiddle
You can use simple sum and max functions for this.
SELECT name,
SUM(distance) AS distance,
MAX(create_date) AS create_date
FROM theTable
WHERE create_date >= #startDate AND create_date < #endDate
GROUP BY name
ORDER BY distance DESC
Query to get total commissions for an employee, and update their totalCommission column in the employee table.
This query is run every few days (batch).
The rules:
1. an employee can only get a maximum of $100/day of commision, if they get more than $100 it just gets set to $100.
Tables:
Employee
(employeeID INT PK, totalCommissions INT, username, ...)
Sale
(saleID INT PK, employeeID INT FK, saleTotal, commission, created DATETIME)
Using SQL Server 2005.
So this query will have to group by day I presume, and use a case statement to set the daily commision to $100 if the sum is > 100 for that day, and then set the total SUM for all days to the Employee.TotalCommission column.
assuming you are limiting the dates somewhere using value of "somedate-goes-here":
update employee set totalcommissions = totalc
from
(
-------------------------------------
-- sum capped commissions by employee
-------------------------------------
select employeeID, sum(sum_commissions) as totalc from
(
---------------------------------------
-- make sure sum is capped if necessary
---------------------------------------
select employeeID
, case when sum_of_c > 100 then 100 else sum_of_c as sum_commisions
from
(
-----------------------------------------------
-- get sum of commissions per day per employee
-----------------------------------------------
select employeeID, sum(commission) as sum_of_c from sale
where created > "somedate-goes-here"
group by employeeID, day(created)
) as x
) as c
group by employeeID
) y
inner join employee on employee.employeeID = y.employeeID