Automatic Age Update in SqlServer - sql-server

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!

Related

How to design a table having age which returns current age of that person when queried after two years in SQL Server?

I want to design a table as below, which returns the current age of a person when queried after two years.
CREATE TABLE Person
(
Person_ID INT IDENTITY(1,1) NOT NULL,
Initial VARCHAR(50) NULL,
Surname VARCHAR(100) NOT NULL,
Age INT NOT NULL
)
For example table has 2 rows
Person_ID Initial Surname Age
-------------------------------
1 AR Rahman 40
2 M Jackson 50
On a select query after two years
select age
from Person
where person_ID = 1
it should return 42
You should store date of birth in your table and always calculate age.
To achieve this you can use calculated column or you will need include calculations in the query itself.
Store date of birth in your table as DATE and use computed column without using persisted keyword because age calculation is non-deterministic as shown in the code below.
CREATE TABLE #Person
(
Person_ID INT IDENTITY(1,1) NOT NULL,
Initial VARCHAR(50) NULL,
Surname VARCHAR(100) NOT NULL,
DOB DATE NULL,
Age AS DATEDIFF(YEAR,DOB,getdate())
)
INSERT INTO #Person
SELECT 'Gyan','Prakash','26-feb-1994'
SELECT * FROM #Person

how to Get previous three months date based on a from date and to date parameter value

We have to compare the sales on given based on the parameter from and to date at last three months.
Create table Net_sales
(terminalid varchar(14),
Region varchar(20),
City varchar(50),
ICC_TRNS_COUNT int,
ICC_AMount money,
Trns_Date datetime)
--SELECT * FROM Net_sales
insert into Net_sales values ('INMAA031000000','SOUTH','CHENNAI',1,5000,'08/01/2019')
insert into Net_sales values ('INMAA031000000','SOUTH','CHENNAI',1,4000,'08/02/2019')
insert into Net_sales values ('INMAA031000000','SOUTH','CHENNAI',1,200,'08/04/2019')
insert into Net_sales values ('INAMD03900030G','WEST','Gujarat',1,52000,'08/01/2019')
insert into Net_sales values ('INAMD03900030G','WEST','Gujarat',1,40700,'08/02/2019')
insert into Net_sales values ('INAMD03900030G','WEST','Gujarat',1,2200,'08/04/2019')
insert into Net_sales values ('INAMD03900030G','WEST','Gujarat',1,52000,'09/01/2019')
insert into Net_sales values ('INAMD03900030G','WEST','Gujarat',1,47000,'09/02/2019')
insert into Net_sales values ('INAMD03900030G','WEST','Gujarat',1,2200,'09/10/2019')
insert into Net_sales values ('INAMD03900030G','WEST','Gujarat',1,52000,'10/01/2019')
insert into Net_sales values ('INAMD03900030G','WEST','Gujarat',1,70000,'10/02/2019')
insert into Net_sales values ('INAMD03900030G','WEST','Gujarat',1,3200,'10/10/2019')
-------------------
DECLARE #FROMDATE DATETIME
DECLARE #TODAY DATETIME
SET #FROMDATE='08/01/2019'
SET #TODAY='10/10/2019'
SELECT
TERMINALID ,
CITY,
REGION,
SUM(ICC_AMOUNT) ICASHDMRAMOUNT
FROM NET_SALES WHERE CONVERT(VARCHAR,TRNS_DATE,101) BETWEEN CONVERT(VARCHAR,#FROMDATE,101) AND CONVERT(VARCHAR,#TODAY,101)
GROUP BY TERMINALID ,
CITY,
REGION
ORDER BY TERMINALID
we need to expected and result
Expected result
TERMINALID CITY REGION ICASHDMRAMOUNT_AUG ICASHDMRAMOUNT_SEP ICASHDMRAMOUNT_OCT
INAMD030001024 Gujarat WEST 94200 94200 94200
INAMD03900030G Gujarat WEST 94900 101200 125200
INMAA031000000 CHENNAI SOUTH 5000 0 0
A few things.
TerminalID INAMD030001024 doesn't exist in your sample data, so it's not in the sample result set.
Your dates are stored as dates, so leave them that way. When you convert them to strings, date functions no longer work properly on them. Also, it's best to use ANSI/ISO standard date format, which is 'YYYY-MM-DD'. Using 'MM/DD/YYYY' could be misinterpreted as 'DD/MM/YYY' depending on the regional settings on your servers. The standard form will always be interpreted correctly by the server.
With that said, your query just requires some conditional aggregation:
SELECT
TERMINALID,
CITY,
REGION,
SUM(CASE WHEN MONTH(TRNS_DATE) = 8 THEN ICC_AMOUNT ELSE 0 END) AS ICASHDMRAMOUNT_AUG,
SUM(CASE WHEN MONTH(TRNS_DATE) = 9 THEN ICC_AMOUNT ELSE 0 END) AS ICASHDMRAMOUNT_SEP,
SUM(CASE WHEN MONTH(TRNS_DATE) = 10 THEN ICC_AMOUNT ELSE 0 END) AS ICASHDMRAMOUNT_OCT
FROM
NET_SALES WHERE TRNS_DATE BETWEEN #FROMDATE AND #TODAY
GROUP BY
TERMINALID ,
CITY,
REGION
ORDER BY
TERMINALID;
Results:
TERMINALID CITY REGION ICASHDMRAMOUNT_AUG ICASHDMRAMOUNT_SEP ICASHDMRAMOUNT_OCT
INAMD03900030G Gujarat WEST 94900 101200 125200
INMAA031000000 CHENNAI SOUTH 9200 0 0
SQL Fiddle: http://sqlfiddle.com/#!18/42bfbc/3/0
If you edit the Fiddle data to include the missing TerminalID, you should get to your precise desired results.
EDIT: If you need this to be a rolling three months, create a variable, maybe #FinalMonth int, set that to the value of MONTH(#TODAY), then in the CASE expressions, use #FinalMonth-2, #FinalMonth-1, #FinalMonth rather than the hard coded values above. Your column names won't have month names in them without doing some dynamic SQL, but _CurrMnth, _PrevMnth, _2ndPrevMnth or something like that would get your point across.

Payroll computation

I need you to help me. I have to do a program that calculates the payroll in Management Sql Server 2014. The program should be something like that:
The salary is the sum of gross salary and paid holidays: Sal = Gross_ Salary + Paid_Holiday
For the computation of the Paid_ Holiday we need:
The salary from the previous 6 months:
Sal_6 + Sal_5 + Sal_4 + Sal_3 + Sal_2 + Sal_1 = Base
With Sal_6 = GrossSal_6 + Paid_Holiday_6 ( as i said above)
...
The number of days worked or holiday days from the previous 6 months:
NOdays_6 + NOdays_5 + NOdays_4 + NOdays_3 + NOdays_2 + NOdays_1 = SumOfDays
The paid holiday is: Paid_Holiday= BASE/SumOfDays * NOdays.
From the database I have the following tables:
Entry ( Identry, Gross_Salary, NOdayworked, Date, IDEmplyee )
Employee (IDEmplyee, Name, DateofEmployment)
Holiday ( IDHoliday, StartDate, FinalDate, IDEmployee)
The employee has an seniority certificate with the last 6 salaries from the previous employer.
Certificate ( IdCertificate, date, Gross_Salary, NOdayworked, Paid_Holiday, NOdays, IDEmployee)
Because I need the last paid holidays and salary to form the gross salary I thought that I should used a temporary table. This table will retain the data from the certificate and the data from Entry
What I have tried so far is the following stored procedure:
create proc payroll
#idemployee int
as
create table #tmp( id int identity(1,1) primary key, date1 date, grosssalary money, idemployee int, nodaysworked int, paidholiday money, noofdays int)
insert into #tmp ( date1 , grosssalary , idemployee , nodaysworked , paidholiday , noofdays )
Select Top 6 Date,
Gross_Salary,
IDEmployee,
NOdayworked,
Paid_Holiday,
IDEmployee
from Certificate
WHERE IDEmployee = #idemployee
ORDER BY Date asc
And after that I have to take for every paidholiday the last 6 Salary
Paid_Holiday= BASE/SumOfDays * NOdays but I don't know exactly how I should do. I thought about a cursor or something.
PS: If you didn't understand please let me know. My mother tongue is not English ( also this program is not available for all the countries.
The program is valid in Romania)

How to render & insert alphabets row within the MS sql server records?

Database Records:
I want to represent as record set using stored procedure.
I have many records likewise in MS SQL DataBase.
It will be Listing record groupby A, B, C .. Z wize..
Automatically insert the Alphabets while got output from SQL Table.
I want below output from procedure..
How it will possible using Stored Procedure..?
You can use LEFT and UNION for this, though you will still get a 3 columns row for the rows that contains only the first letter:
Create and populate sample table (Please save us this step in your future questions)
DECLARE #T as TABLE
(
Name varchar(20),
Location varchar(20),
CreatedOn date
)
INSERT INTO #T VALUES
('Alex macwan', 'New york', '2015-12-10'),
('Jone Dinee', 'Denmark', '2016-05-01'),
('Jolly llb', 'USA', '2016-01-02'),
('Amin Mark', 'India', '2015-01-08'),
('Ben Denis', 'Brazil', '2015-10-02')
The query:
SELECT Name, Location, CreatedOn
FROM #T
UNION
SELECT LEFT(Name, 1), NULL, NULL
FROM #T
ORDER BY Name
Results:
Name Location CreatedOn
-------------------- -------------------- ----------
A NULL NULL
Alex macwan New york 2015-12-10
Amin Mark India 2015-01-08
B NULL NULL
Ben Denis Brazil 2015-10-02
J NULL NULL
Jolly llb USA 2016-01-02
Jone Dinee Denmark 2016-05-01

First Transaction Date and Amount and Latest Transaction Date and Amount

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)

Resources