SQL
--Way 1
select CustomerEmail, OrderDate
into #tempOrders
from Orders
where Status = 'Shipped'
select * from #tempOrders
--Way 2
drop table #tempOrders
create table #tempOrders
(
CustomerEmail nvarchar(500),
OrderDate datetime
)
insert into #tempOrders
select CustomerEmail, OrderDate
from Orders
where Status = 'Shipped'
select * from #tempOrders
RealExamples
Data
-- Create the departments table
CREATE TABLE departments (
dept_no INT NOT NULL PRIMARY KEY,
dept_name VARCHAR(100) NOT NULL,
dept_location VARCHAR(100) NOT NULL
);
-- Insert some test data into the departments table
INSERT INTO departments VALUES
(1, 'Sales', 'Chicago'),
(2, 'Marketing', 'London'),
(3, 'IT', 'Toronto');
-- Create the employees table
CREATE TABLE employees (
emp_id INT NOT NULL PRIMARY KEY,
emp_name VARCHAR(100) NOT NULL,
emp_contact VARCHAR(25),
salary INT NOT NULL,
mgr_emp_id INT,
dept_no INT NOT NULL,
FOREIGN KEY (mgr_emp_id) REFERENCES employees (emp_id),
FOREIGN KEY (dept_no) REFERENCES departments (dept_no)
);
-- Insert some test data into the employees table
INSERT INTO employees VALUES
(1, 'Alice', '[email protected]', 5000, NULL, 1),
(2, 'Bob', '[email protected]', 6000, 1, 1),
(3, 'Charlie', '[email protected]', 4000, 2, 2),
(4, 'David', '[email protected]', 5000, NULL, 2),
(5, 'Eve', '[email protected]', 3000, 4, 3),
(6, 'Frank', '[email protected]', 4000, NULL, 3);
Temporary Table
--select * from departments
--select * from employees
select
d.dept_no, d.dept_name, avg(e.salary) as 'avg_salary'
into #deptavg
from departments d
join employees e on d.dept_no = e.dept_no
group by d.dept_no, d.dept_name
--select * from #deptavg
select
e.emp_name as 'Name',
e.salary as 'Salary',
d.dept_name as 'Department',
d.avg_salary as 'Avg_Salary',
ISNULL(em.emp_name,'') as 'Manager'
from employees e
join #deptavg d on d.dept_no = e.dept_no
left join employees em on e.mgr_emp_id = em.emp_id
drop table #deptavg