Sei sulla pagina 1di 36

My role & responsibilities in my current company is to understand the

client requirements and plan, develop, maintain and deploy the software
project, help testers to test the particular software application, and help
and co-operate with other team members.

1)Show the customer name for all customers who have ever made a payment over
$100,000

Ans:SELECT customerName

FROM customers c

WHERE EXISTS ( SELECT 1 FROM payments p WHERE p.customerNumber =


c.customerNumber AND p.amount > 100000)

2) Show the product code, product name, and quantity in stock of all products that
have a purchase price greater than the average.

ANS=SELECT productCode

, productName

, quantityInStock

FROM products
WHERE buyPrice > (SELECT AVG(buyPrice) FROM products)

3) Show the product name, product description, and product line for the product in
each product line that has the highest gross revenue.

AnsWITH cte1 AS (

SELECT productCode

, SUM(quantityOrdered*priceEach) AS totalOrdered

FROM orderdetails

GROUP BY productCode

SELECT productName

, productDescription

, productLine

FROM products p

JOIN cte1 ON cte1.productCode = p.productCode

WHERE cte1.totalOrdered =

(SELECT MAX(totalOrdered)

FROM cte1

JOIN products p2 ON p2.productCode = cte1.productCode

WHERE p2.productLine = p.productLine)

4) Show the employee first name, last name, and job title for all employees with
the job title of Sales Rep.

ANS=

SELECT firstName, lastName, jobTitle

FROM employees

WHERE jobTitle= 'Sales Rep'

5) We need to get some feedback from all of the employees who have sold Harley
Davidson Motorcycles. Get a report of the employee first names and emails for all
employees who have ever sold a Harley.

ANS= SELECT DISTINCT e.firstName

, e.email
FROM products p JOIN orderdetails od ON p.productCode = od.productCode

JOIN orders o ON o.orderNumber = od.orderNumber

JOIN customers c ON c.customerNumber = o.customerNumber

JOIN employees e ON e.employeeNumber = c.salesRepEmployeeNumber

WHERE p.productName LIKE '%Harley%'

6) We want to display information about customers from France and the USA.
Show the customer name, the contact first and last name (in the same column),
and the country for all of these customers.

ANS=

SELECT customerName

, contactFirstName + ' ' + contactLastName AS 'Contact Name'

, country

FROM customers

WHERE country IN ('France', 'USA')

7) We want to dig into customer order history. Show each customer name, along
with date of their initial order and their most recent order. Call the initial order
'first_order' and the last one 'last_order'. Also include any customers who have
never made an order.

Ans-SELECT c.customerName

, MIN(orderDate) AS 'first_order'

, MAX(orderDate) AS 'last_order'

FROM customers c

LEFT JOIN orders o ON c.customerNumber = o.customerNumber

GROUP BY c.customerName

8) Show each office city, and the average number of orders per employee per
office (without displaying the individual employee average). For example, say
office ABC has 2 employees. Employee #1 was responsible for 2 orders, and
employee #2 was responsible for 6 orders. Then your result set should
show ABC for the first column (city), and 4 for the second column (avg orders per
employee per office: (2+6)/2).

Ans-WITH employee_orders AS (

SELECT e.officeCode

, e.employeeNumber

, COUNT(o.orderNumber) AS order_count
FROM employees e

LEFT JOIN customers c ON c.salesRepEmployeeNumber = e.employeeNumber

LEFT JOIN orders o ON o.customerNumber = c.customerNumber

GROUP BY e.officeCode, e.employeeNumber

SELECT o.city

, AVG(order_count) AS avg_orders

FROM employee_orders eo

JOIN offices o ON eo.officeCode = o.officeCode

GROUP BY o.city

9) Show each product line and the number of products in each product line, for all
product lines with more than 20 products.

Ans-SELECT p1.productLine

, COUNT(*) AS num_products

FROM products p

JOIN productLines p1 ON p.productLine = p1.productLine

GROUP BY p1.productLine

HAVING COUNT(*) > 20

10) We want to get an idea of the status of the orders of our customers. Show
each customer number, and then the number of orders they have by status type.
So you will have a column for customer number, and then one column each
for shipped, in process, cancelled, disputed, resolved, and on hold.

ANS=SELECT customerNumber

, SUM(CASE WHEN status = 'shipped' THEN 1 ELSE 0 END) AS shipped

, SUM(CASE WHEN status = 'in process' THEN 1 ELSE 0 END) AS 'in process'

, SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) AS 'cancelled'

, SUM(CASE WHEN status = 'disputed' THEN 1 ELSE 0 END) AS 'disputed'

, SUM(CASE WHEN status = 'resolved' THEN 1 ELSE 0 END) AS 'resolved'

, SUM(CASE WHEN status = 'on hold' THEN 1 ELSE 0 END) AS 'on hold'

FROM orders

GROUP BY customerNumber
11) What is the smallest payment from 2004?

Ans=SELECT MIN(amount) AS smallest_payment_2004

FROM payments

WHERE YEAR(paymentDate) = 2004

12) We want to make sure the company is taking care of top clients. We need to
find our most profitable orders that haven't shipped yet, so that we can give those
customers extra attention. Find the 5 biggest orders (largest subtotal) that have
not shipped yet. Display in a report the employee name, customer name, order
number, order subtotal, and status for those 5 largest subtotals.

Ans=SELECT TOP 5 e.firstName + ' ' + e.lastName AS employee_name

, c.customerNumber

, od.orderNumber

, (od.quantityOrdered*od.priceEach) AS order_subtotal

, o.status

FROM orderdetails od

JOIN orders o ON od.orderNumber = o.orderNumber

JOIN customers c ON c.customerNumber = o.customerNumber

JOIN employees e ON e.employeeNumber = c.salesRepEmployeeNumber

WHERE o.status <> 'shipped'

ORDER BY order_subtotal DESC

13) Find the average number of days before the required date that shipped orders
are shipped. Round to 2 decimal places.

Ans=SELECT CONVERT( DECIMAL(10, 2), AVG( CONVERT( DECIMAL(10,2), DATEDIFF(dd,


requiredDate, shippedDate) ) ) ) AS AVG_SHIPPED_BEFORE_DATE

FROM orders

WHERE status = 'shipped'

14) We want to create a transaction history for customer # 363 (we consider
orders and payments as transactions). Show a list of their customer number,
order/payment date, and order/payment amount. So if they made an order on
1/12 and a payment on 1/15, then you would show the 1/12 order on the first
row, and the 1/15 payment on the second row. Show their order amounts as
negative.

ANS=SELECT o.customerNumber

, o.orderDate
, SUM(quantityOrdered*priceEach)*-1 AS subtotal

FROM orderdetails od

JOIN orders o ON od.orderNumber = o.orderNumber

WHERE o.customerNumber = 363

GROUP BY o.customerNumber, o.orderDate

UNION

SELECT p.customerNumber

, p.paymentDate

, p.amount

FROM payments p

WHERE p.customerNumber = 363

15) Show a list of all the countries that customers come from.

Ans=SELECT DISTINCT country

FROM customers

16) We want to see how many customers our employees are working with. Show a
list of employee first and last names (same column), along with the number of
customers they are working with.

Ans=SELECT (e.firstName + ' ' + e.lastName) AS 'Employee Name'

, COUNT(*) AS '# of Customers'

FROM employees e

JOIN customers c ON e.employeeNumber = c.salesRepEmployeeNumber

GROUP BY (e.firstName + ' ' + e.lastName)

ORDER BY COUNT(*) DESC;

17) Find a list of invalid employee email addresses.

Ans=SELECT email

FROM employees

WHERE email NOT LIKE '%_@__%.__%'

18) We want to see information about our customers by country. Show a list of
customer countries, the number of customers from those countries, and the total
amount of payments those customers have made.

ANS=WITH country_totals
AS

SELECT country

, COUNT(*) AS customer_count

FROM customers

GROUP BY country

SELECT ct.*

, SUM(p.amount) AS payment_total

FROM payments p JOIN customers c ON p.customerNumber = c.customerNumber

JOIN country_totals ct ON ct.country = c.country

GROUP BY ct.country, ct.customer_count

ORDER BY customer_count DESC

19) The company needs to see which customers still owe money. Find customers
who have a negative balance (amount owed greater than amount paid). Show the
customer number and customer name.

Ans=SELECT customerNumber

, customerName

FROM customers c

WHERE

SELECT SUM(quantityOrdered*priceEach) AS order_subtotal

FROM orderdetails od

JOIN orders o ON od.orderNumber = o.orderNumber

WHERE o.customerNumber = c.customerNumber

GROUP BY o.customerNumber

>

SELECT SUM(p.amount) AS payment_subtotal


FROM payments p

WHERE p.customerNumber = c.customerNumber

GROUP BY p.customerNumber

20)The company wants to see which orders have had issues. Grab everything from
the orders table where the comments include the word difficult.

Ans=SELECT *

FROM orders

WHERE comments LIKE '%difficult%';

21) Corporate wants to see if there is any correlation between customer success
and local sales reps. To start, we want you to find which customers work with
employees in their home state. Show the customer names and states of those that
apply.

Ans-SELECT customerName

, c.state

FROM customers c

JOIN employees e ON e.employeeNumber = c.salesRepEmployeeNumber

JOIN offices o ON o.officeCode = e.officeCode

WHERE o.state = c.state

22) The boss needs to see a list of product vendors, and the number of items they
have in stock. Show the vendors with the most items in stock first.

Ans=SELECT productVendor

, SUM(quantityInStock) AS vendor_total

FROM products

GROUP BY productVendor

ORDER BY SUM(quantityInStock) DESC

23) CHALLENGE: This is a continuation of challenge #14. To recap, in challenge


#14 we want to see a history of orders and payments by customer # 363.This
time, we want the same information (customer number, order/payment date, and
order/payment amount), but we also want to include a running total of their
balance as a fourth column.

Ans=WITH transaction_history AS

(
SELECT o.customerNumber

, o.orderDate

, SUM(quantityOrdered*priceEach)*-1 AS subtotal

FROM orderdetails od

JOIN orders o ON od.orderNumber = o.orderNumber

WHERE o.customerNumber = 363

GROUP BY o.customerNumber, o.orderDate

UNION

SELECT p.customerNumber

, p.paymentDate

, p.amount

FROM payments p

WHERE p.customerNumber = 363

SELECT th.*

, SUM(subtotal) OVER(ORDER BY orderDate) AS running_total

FROM transaction_history th

24) Find the product that has been ordered the most. Show the product name, and
how many times it has been ordered.

ANS=WITH total_order_details AS (

SELECT productCode

, SUM(quantityOrdered) AS total_orders

FROM orderdetails

GROUP BY productCode

SELECT p.productName

, tod.total_orders

FROM products p

JOIN total_order_details tod ON p.productCode = tod.productCode

WHERE tod.total_orders = ( SELECT MAX(total_orders) FROM total_order_details );


25) Find dates where both orders and payments were made

Ans-SELECT DISTINCT o.compare_date

FROM ( SELECT orderDate AS compare_date FROM orders ) o

JOIN ( SELECT paymentDate AS compare_date FROM payments ) p ON o.compare_date =


p.compare_date

26) Show a list of all transaction dates, and the combined number of orders and
payments made on those days.

Ans=WITH transactions AS(

SELECT orderDate as transaction_date

, 'order' AS transaction_type

FROM orders

UNION ALL

SELECT paymentDate as transaction_date

, 'payment' AS transaction_type

FROM payments

SELECT transaction_date

, COUNT(*) AS transaction_count

FROM transactions

GROUP BY transaction_date;

27) Display a percentage of customers who have made orders of more than one
product. Please round your answer to 2 decimal places.

Ans=WITH customer_product_information AS (

SELECT c.customerNumber

, od.productCode

FROM customers c

LEFT JOIN orders o ON c.customerNumber = o.customerNumber

LEFT JOIN orderdetails od ON o.orderNumber = od.orderNumber

, customer_product_aggregation AS (

SELECT customerNumber
, COUNT( DISTINCT productCode ) AS product_count

, CONVERT( DECIMAL(28, 7), CASE WHEN COUNT( DISTINCT


productCode ) >= 2 THEN 1 ELSE 0 END ) AS qualified_customer

FROM customer_product_information

GROUP BY customerNumber

SELECT CONVERT( DECIMAL(28, 2), SUM( qualified_customer ) / COUNT(*) ) AS 'Qualified


Customer Percentage'

FROM customer_product_aggregation

28) CHALLENGE: Find the number of customers that each management-level (not
sales reps) employee is responsible for. This includes customers tied directly to
the managers, as well as customers tied to employees that report to the
managers. Show the employee name (first and last), their job title, and the
number of customers they oversee.

Ans=WITH cust_per_emp AS

SELECT e.reportsTo

, COUNT(*) cust_count

FROM employees e

JOIN customers c ON e.employeeNumber = c.salesRepEmployeeNumber

GROUP BY e.reportsTo

SELECT boss.firstName + ' ' + boss.lastName AS employee_name

, boss.jobTitle

, emp.cust_count

FROM cust_per_emp emp

JOIN employees boss ON emp.reportsTo = boss.employeeNumber

29) CHALLENGE: We want a report of employees and orders that are still in the
works (not shipped, cancelled, or resolved). Show the employee name (first and
last), customer number, order number, and the status of the order.

Ans=SELECT e.firstName + ' ' + e.lastName as employee_name

, c.customerNumber

, o.orderNumber
, o.status

FROM employees e

JOIN customers c ON e.employeeNumber = c.salesRepEmployeeNumber

JOIN orders o ON o.customerNumber = c.customerNumber

WHERE status NOT IN ('shipped', 'cancelled', 'resolved')

30) CHALLENGE: Show all order amounts over $60,000. Order them in ascending
order.

ANS=SELECT DISTINCT SUM(quantityOrdered*priceEach) AS orderPrice

FROM orderdetails

GROUP BY orderNumber

HAVING SUM(quantityOrdered*priceEach) > 60000

ORDER BY orderPrice

31) Show all order numbers for orders consisting of only one product.

ANS=SELECT orderNumber

FROM orderdetails

GROUP BY orderNumber

HAVING COUNT(productCode) = 1

32) We want to see what comments our customers are leaving. Show all order
comments (leave out the ones where there are no comments)

ANS=SELECT comments

FROM orders

WHERE comments IS NOT NULL

33) Today we are going to work with the WORLD database. Show all of the country
and countrylanguage information for countries that speak french and have a GNP
greater than 10,000.

ANS=SELECT *

FROM country c

JOIN countryLanguage cl ON cl.countryCode = c.code

WHERE cl.language = 'french'

AND c.gnp>10000
34) Using the WORLD database, show the number of countries where English is an
official language, and then show the number of countries where English is spoken.
Display each result in its own column (2 total).

ANS=SELECT (SELECT COUNT(*) FROM countryLanguage WHERE isOfficial = 'T' and


Language = 'English') AS official_English_count

, COUNT(*) AS total_English_count

FROM countryLanguage

WHERE Language = 'English'

35) Using the WORLD database, we want to see if there is a correlation between
population and life expectancy. Show each country's name, population rank (1
being the highest, and on down from there), life expectancy rank (same), and
overall score (population rank + life expectancy rank).

Ans=WITH rank_base AS

SELECT name

, RANK() OVER (ORDER BY population DESC) AS pr

, RANK() OVER (ORDER BY LifeExpectancy DESC) AS ler

FROM country

SELECT name

, pr AS 'Population Rank (DESC)'

, ler AS 'Life Expectancy Rank (DESC)'

, pr + ler AS 'Total Rank'

FROM rank_base

ORDER BY 'Total Rank'

36) Using the WORLD database, I noticed that the United States doesn't have Thai
listed as one of their languages. After looking through census data, it shows that
0.3 % of people in the USA speak Thai at home. So let's add it to the list in our
query result. Show all information about the languages spoken in the USA, and
add a row to your results including Thai as well.

Ans=select *

from countrylanguage

where countrycode = 'usa'

union all
select 'USA', 'Thai', 'F', '.3'

37) Using the WORLD database, show the country name and population for the
second most populated country.

Ans=WITH pop_rank AS

SELECT name

, population

, RANK() OVER (ORDER BY population DESC) AS ranking

FROM country

SELECT name

, population

FROM pop_rank

WHERE ranking = 2

38) Using the WORLD database, we want to see which languages account for more
than 50% of the population in more than 5 countries. Show the language and the
number of countries that fit this criteria.

Ans=SELECT language

, COUNT(*) AS country_count

FROM countrylanguage

WHERE percentage>50

GROUP BY language

HAVING COUNT(*)>5

39) Using the WORLD database, we want to see the countries with the lowest
population density. Display the name, density ranking, and population per surface
area for the 10 countries with the lowest population density.

Ans=WITH pop_area_data AS

SELECT name

, SurfaceArea/Population AS Pop_Per_Area

FROM country
WHERE Population <> 0

, pop_area_ranking AS

SELECT name

, RANK() OVER (ORDER BY Pop_Per_Area) AS pa_rank

, Pop_Per_Area

FROM pop_area_data

SELECT *

FROM pop_area_ranking

WHERE pa_rank <= 10

40) Using the WORLD database, show all the country information we have about
the country with the highest life expectancy.

Ans=SELECT *

FROM country

WHERE LifeExpectancy =

(SELECT MAX(LifeExpectancy) FROM country)

41) Using the WORLD database, show all the country information we have about
the country with the highest life expectancy for each continent.

Ans=SELECT *

FROM country c1

WHERE LifeExpectancy =

(SELECT MAX(LifeExpectancy)

FROM country c2

WHERE c1.continent = c2.continent)

42) Using the WORLD database, show all the country information for countries
whose GNP has decreased.

Ans=SELECT *

FROM country

WHERE GNPOld > GNP


43) Using the WORLD database, show all country information for the top 3 largest
(area) countries per continent.

Ans=WITH country_rank AS

SELECT RANK() OVER (PARTITION BY continent ORDER BY SurfaceArea DESC) AS ranking,


*

FROM country

SELECT *

FROM country_rank

WHERE ranking < 4

44) Using the WORLD database, we want to see the top 3 most populated cities for
the top 3 most populated countries from each continent. Show the city ranking,
city name, city population, country ranking, country name, and continent for each
city.

Ans=WITH country_rank AS

SELECT RANK() OVER (PARTITION BY continent ORDER BY SurfaceArea DESC) AS


country_ranking

, c.code

, c.name AS country_name

, c.continent

FROM country c

), top_three_country AS

SELECT *

FROM country_rank

WHERE country_ranking < 4

), top_three_city AS

SELECT RANK() OVER (PARTITION BY countrycode ORDER BY ci.population DESC) AS


city_ranking
, ci.name AS city_name

, ci.population

, tt.country_ranking

, tt.country_name

, tt.continent

FROM city ci

JOIN top_three_country tt ON tt.code = ci.countrycode

SELECT *

FROM top_three_city

WHERE city_ranking < 4

ORDER BY continent, country_ranking, city_ranking

45) Using the WORLD database, show the various government types and the
number of countries that use each type. Display them from the most used to the
least used.

Ans=SELECT GovernmentForm

, COUNT(*) AS gov_count

FROM country

GROUP BY GovernmentForm

ORDER BY COUNT(*) DESC

46) Using the WORLD database, we want to see the countries that have an above
average population. Display the country name and population.

Ans=SELECT name

, population

FROM country

WHERE population > (SELECT AVG(CAST(population AS BIGINT)) FROM country)

47) Display the first name, job title and office code of employees who have office
code 2, 4 and 7 respectively. Order them by office code ascending.

Ans=select firstname

,jobtitle

,officecode
from employees

where officecode in (2,4,7)

order by officecode asc;

48) Find the total number of customers that each employee represents. Prepare a
report in this format "Andy Fixter represents 5 customers". Name the column
No. of customers and order it by customer count ascending.
Ans=select concat(e.firstname,' ', e.lastname, ' represents ', count(c.customernumber), '
customers.') as "No. of customers"
from employees e
join customers c on e.employeenumber=c.salesrepemployeenumber
group by c.salesrepemployeenumber, e.firstname, e.lastname
order by count(c.customernumber);

49) The check we sent out for the third highest amount has been misplaced! We
want information about that check. Write a query to find third highest check
amount and display customer name, check number, amount and payment date.

Ans=select c.customername

, p.checknumber

, p.amount

, p.paymentdate

from customers c

join payments p on c.customernumber=p.customernumber

where (select count(distinct(p1.amount))

from payments p1

where p1.amount>p.amount)=2;

50) How many countries have names that are seven characters long, where the
name also starts with the letter A or B?

Ans=SELECT count(len(name)) FROM country where name like '[A-B]%' and len(name)=7;

51) Create a query which displays the total number of products shipped in the
years 2003, 2004 and 2005. Display the result in horizontal rows, with the year as
the column heading and total products under the respective column year.

Ans=select count(case when year(o.shippeddate)=2003 then ord.productcode end) as


"2003"

, count(case when year(o.shippeddate)=2004 then ord.productcode end) as "2004"

, count(case when year(o.shippeddate)=2005 then ord.productcode end) as "2005"


from orders o

join orderdetails ord on o.ordernumber=ord.ordernumber

where o.status='Shipped'

and year(o.shippeddate) is not null;

52) Display the full name of Sales Rep whose office code is 6. Result should be in
the format of "firstName lastName" (space between the names).

Ans= select concat(firstname,' ',lastname)

from employees

where jobtitle='Sales Rep' and officecode=6;

53) Which product has order status On Hold? Display the name of the product
and its status.

Ans=select p.productname,o.status

from products p

join orderdetails ord on p.productcode=ord.productcode

join orders o on ord.ordernumber=o.ordernumber

where o.status='On Hold';

54) Name the customer who has the higest average payment amount among all
customers. Show both the customer name and their average payment amount.

Ans=SELECT c.customername

,avg(p.amount) as "Maximum average"

from payments p

join customers c on c.customernumber=p.customernumber

group by c.customername,p.customernumber

having avg(p.amount)=(select max(avgage)

from (SELECT avg(amount) as avgage

from payments

group by customernumber) as cust_pay);

55) Get a count of the total number of customer as Total Customers, and a
summation of their credit limit as Total Credit from the customers table.

Ans=SELECT count(customernumber) as "Total Customers"

,sum(creditlimit) as "Total Credit"


from customers;

56) Find the products which were shipped in the last 6 months of year 2004.
Display the product name and shipped date.

Ans=select distinct p.productname,o.shippeddate,o.status

from products p join orderdetails ord on p.productcode=ord.productcode

join orders o on ord.ordernumber=o.ordernumber

where datepart(mm,o.shippeddate)>6

and datepart(yy,o.shippeddate)=2004

and o.status='Shipped';

57) Retailer Company wants to organize their customers into Regular, Premium,
Sliver and Gold categories. Customers who paid an average amount between
$1,000-$9,999 should be in the Regular category. $10,000-$29,999 is Premium,
$30,000-$39,999 is Silver, and $40,000 and above would be a gold customer.
Design a query for this scenario, displaying customer name and their category.
Order the category Gold to Regular.

Ans=select c.customername,

case when avg(p.amount) BETWEEN 1000 and 9999 then 'Regular'

when avg(p.amount) BETWEEN 10000 and 29999 then 'Premium'

when avg(p.amount) BETWEEN 30000 and 39999 then 'Silver'

else 'Gold' end as Category

from payments p,customers c

where c.customernumber=p.customernumber

group by c.customername,c.customernumber

order by avg(p.amount) desc;

58) Increase the credit limit by $10,000 for customers who have a credit limit less
than or equal to $65,700.00 (pre-increment). Show the customer name and
incremented credit limit as Credit Increment.

Ans=select customername

,creditlimit+10000 as "Credit Increment"

from customers

where creditlimit<=65700.00;

59) We want to see orders that are in process. Display the product name, require
date, shipped date and status of these orders. If there is no shipped date then it
should display Unavailable.
Ans=select p.productname

,o.requireddate

,isnull(convert(varchar(25),o.shippeddate,120),'Unavailable') as shippeddate

,o.status

from products p,orderdetails ord,orders o

where p.productcode=ord.productcode and ord.ordernumber=o.ordernumber

and o.status='In process';

60) List all distinct job titles other than Sales Rep from the employees table.

Ans=select distinct(jobtitle)

from employees

where jobtitle <> 'Sales Rep';

61) Find the office state of all employees who represents customers from
Queensland. Show employee last names, their office state, and the corresponding
customer name. If office state is not mentioned it should display country.

Ans=select e.lastname

,coalesce(o.state,o.country) Region

,c.customername

from employees e

join customers c on c.salesrepemployeenumber=e.employeenumber

join offices o on e.officecode=o.officecode

where c.state='Queensland';

62) Show all information for those employees whose last name starts with K.

Ans=SELECT *

FROM employees

WHERE lastname LIKE '[K]%';

63) Find the products that were shipped in last 6 months of the year 2004. Display
product name and shipped date, ordering by month ascending.

Ans=SELECT distinct p.productname

,o.shippeddate

FROM products p

JOIN orderdetails ord ON p.productcode=ord.productcode


JOIN orders o ON ord.ordernumber=o.ordernumber

WHERE datepart(mm,o.shippeddate)>6

AND datepart(yyyy,o.shippeddate)=2004

AND o.status='Shipped'

ORDER BY shippeddate;

64) Find the total number of people that report to each employee. Order it by total
number of reporting descending.

Ans=SELECT m.firstname

,COUNT(e.firstname) as total_reporter

FROM employees e

JOIN employees m ON e.reportsto=m.employeenumber

GROUP BY m.firstname;

65) Find the customer names for customers that are not associated with a sales
representative.

Ans=SELECT customername

FROM customers

WHERE salesrepemployeenumber IS NULL;

66) Find all the employees whose name start with D, M and J. Only display
their first names and order the result by first name.

Ans=SELECT firstname

FROM employees

WHERE SUBSTRING(firstname,1,1) in ('D','M','J')

ORDER BY firstname ;

67) Display all the customers who are assigned to and not assigned to a sales
representative, with the unrepresented customers displayed last. Show the
customer name and employee first name columns.

Ans=select c.customername

,e.firstname as salesrep

from employees e

right outer join customers c

on e.employeenumber=c.salesrepemployeenumber
order by e.firstname DESC;

68) The company decided to give a bonus to the employees who work as sales
representatives. Calculate a bonus that is 10% of the average amount paid by the
respective customer for that sales representative. Display employees first name,
customer name, total amount paid by that customer as Amount, and the bonus
in a column named 10% Bonus. You should have a row for each sales rep -
customer relationship.

Ans=select e.firstname

,c.customername

,sum(p.amount) as Amount

, (0.1*avg(amount)) as "10% Bonus"

from customers c

join employees e on c.salesrepemployeenumber=e.employeenumber

join payments p on c.customernumber=p.customernumber

group by e.firstname

,c.customername;

69) Find out the maximum average amount paid by the customer. Round the result
up to two decimal points. Hint : First calculatethe average amount paid then find
out its max.

Ans=select round(max(average),2)

from (

SELECT avg(amount) as average

from payments

group by customernumber

) as cust_pay;

70) What is the highest quantity in stock for each product line? Show each product
line, along with the highest quantity in stock for each product line.

Ans=select productline

, max(quantityInStock)

from products

group by productline ;

71) Calculate the total buy price from the products table and round the result to
one decimal place.
Ans=select round(sum(buyPrice),1)

from products;

72) Create a query which displays the total number of products shipped in the
years 2003, 2004 and 2005 combined. Also have a column for each of those years
with the total number of products shipped in each year respectively. Your results
should display in the following format Total 2003 2004 2005 -----------------------
------------------------------------------------------ x x x x

Ans=select (select sum(product)

from (select count(ord.productcode) product

from orders o,orderdetails ord

where o.ordernumber=ord.ordernumber and o.status='Shipped'

and year(o.shippeddate) is not null

group by year(o.shippeddate)) as i1) as Total,

count(case when year(o.shippeddate)=2003 then ord.productcode end) as "2003",

count(case when year(o.shippeddate)=2004 then ord.productcode end) as "2004",

count(case when year(o.shippeddate)=2005 then ord.productcode end) as "2005"

from orders o

join orderdetails ord on o.ordernumber=ord.ordernumber

where o.status='Shipped'

and year(o.shippeddate) is not null;

73) Increase the credit limit by $10,000 for those customers who have a credit
limit greater than or equal to $65,700.00. Show only the customer name and
credit limit as Credit Increment.

Ans=select customername

, creditlimit+10000 as "Credit Increment"

from customers

where creditlimit>=65700.00;

74) What is the highest quantity in stock for each product line? Show each product
line, along with the highest quantity in stock for each product line.

Ans=select productline

, max(quantityInStock)
from products

group by productline ;
75) Create a report to know which employee is reporting to whom. Capitalize the
entire first name of the person being reported to. For example "Mary reports to
DIANE"

Ans=select concat(e.firstname,' reports to ',upper(m.firstname))

from employees e

join employees m on e.reportsto=m.employeenumber;


76) Write a query that will return all records from the employees table where
there are no records in the contacts table for the matching columns
contactlastname and contactfirstname. Hint: Use NOT Exist clause.

Ans=SELECT *

FROM employees e

WHERE Not EXISTS (SELECT *

FROM customers c

WHERE e.lastname = c.contactlastname

AND e.firstname = c.contactfirstname);


77) Find all customer information for customers who have never made an order.

Ans=SELECT *

FROM customers c

WHERE NOT EXISTS

(SELECT 1

FROM orders o

WHERE o.customerNumber = c.customerNumber)


78) We want to see the amounts for some of our biggest payments. Show the
amounts for the 5th to 10th largest payments, from highest to lowest.

Ans=WITH amount_order AS

(
SELECT ROW_NUMBER() OVER (ORDER BY amount DESC) AS ordering

, amount

FROM payments

SELECT *

FROM amount_order

WHERE ordering BETWEEN 5 and 10

79) FInd the number of times the movie "Agent Truman" has been rented.

Ans=SELECT COUNT(*)

FROM rental

WHERE inventory_id IN (

SELECT inventory_id FROM inventory WHERE film_id = 6)

80) We want to see all movies that have more than 10 actors/actresses. Show the
film_id, title, and number of actors for each film that meets this criteria.

Ans=SELECT f.film_id

, f.title

, COUNT(actor_id)

FROM film f

JOIN film_actor fa ON fa.film_id = f.film_id

GROUP BY f.film_id, f.title

HAVING COUNT(fa.actor_id) > 10

81) Find information about the most expensive rental. If there are more than one
rental at the same price, then go with the most recent one. Show the first and last
name of the customer with this rental, along with their rental id.

Ans=SELECT first_name, last_name, rental_id

FROM customer c

JOIN rental r ON r.customer_id = c.customer_id

WHERE rental_id =

(
SELECT rental_id

FROM

SELECT TOP 1 payment_date, MAX(amount) AS rental_amount, rental_id

FROM payment

GROUP BY payment_date, rental_id

ORDER BY MAX(amount) DESC, payment_date DESC

)a

82) Find the most expensive rental. If there are ties, go with the most recent one.
Then show that rental id, along with the prior and next rentals (by payment date).

Ans=WITH rental_amount_rank AS (

SELECT rental_id

, customer_id

, payment_date

, amount

, RANK() OVER( ORDER BY amount DESC ) AS amount_rank_desc

, ROW_NUMBER() OVER( ORDER BY payment_date DESC) AS payment_date_desc

FROM payment

), rental_date_rank AS (

SELECT rental_id

, customer_id

, payment_date

, amount

, amount_rank_desc

, payment_date_desc

, ROW_NUMBER() OVER( PARTITION BY amount_rank_desc ORDER BY


payment_date DESC) AS amount_payment_date_desc

FROM rental_amount_rank

), rental_assoc AS (
SELECT rental_id

, customer_id

, payment_date

, amount

, amount_rank_desc

, payment_date_desc

, amount_payment_date_desc

, LAG( rental_id ) OVER( ORDER BY payment_date_desc ) AS previous_rental_id

, LEAD( rental_id ) OVER( ORDER BY payment_date_desc ) AS next_rental_id

FROM rental_date_rank

SELECT TOP 1 *

FROM rental_assoc

WHERE amount_rank_desc = 1

ORDER BY amount_payment_date_desc

83) Create a breakdown of films by rental price. We want to see how many films
are rented for between 0 and $0.99. Then $1 - $1.99, and $2 - $2.99, on up to
$4.99.

Ans=SELECT SUM(CASE WHEN rental_rate BETWEEN 0 AND 0.99 THEN 1 ELSE 0 END) AS
[0-0.99]

, SUM(CASE WHEN rental_rate BETWEEN 1 AND 1.99 THEN 1 ELSE 0 END) AS [1-1.99]

, SUM(CASE WHEN rental_rate BETWEEN 2 AND 2.99 THEN 1 ELSE 0 END) AS [2-2.99]

, SUM(CASE WHEN rental_rate BETWEEN 3 AND 3.99 THEN 1 ELSE 0 END) AS [3-3.99]

, SUM(CASE WHEN rental_rate BETWEEN 4 AND 4.99 THEN 1 ELSE 0 END) AS [4-4.99]

FROM film

84) Show all orderdates with a time attached. Set the time to 8 AM (don't need to
show AM though) for all of the orderdates.

Ans=SELECT DATEADD(hh, 8, CAST(orderdate AS datetime)) AS [Order Date and Time]

FROM orders

85) Show the product code, quantity in stock, and buy price for every 5th product
(ordered by product code) in the products table.
Ans=WITH orderingTable AS

SELECT ROW_NUMBER() OVER (ORDER BY productCode) AS productCodeOrder

, productCode

, quantityInStock

, buyPrice

FROM products

SELECT productCode

, quantityInStock

, buyPrice

FROM orderingTable

WHERE productCodeOrder % 5 = 0

86) Show the 3 smallest and 3 largest payment_id numbers. So if the smallest 3
are 1, 2, and 3, and the largest are 55, 56, and 57, then show all of them in a
series of rows in one column.

Ans=SELECT *

FROM (SELECT TOP 3 payment_id

FROM payment

ORDER BY payment_id) a

UNION ALL

SELECT *

FROM (SELECT TOP 3 payment_id

FROM payment

ORDER BY payment_id DESC) b

87) Find the countries that have more than 10 languages but less than
100,000,000 people. Show the country name, # of languages, and population.

Ans=SELECT c.name

, a.numLang
, c.population

FROM country c

JOIN

SELECT countryCode

, COUNT(*) AS numLang

FROM countryLanguage

GROUP BY countryCode

HAVING COUNT(*) > 10

) a ON a.countryCode = c.code

WHERE c.population < 100000000


88) We want to see the country that has the highest population, and the one with
the smallest population. Show the population rank (1 being the most populated),
name, and population for these 2 countries.

Ans=WITH population_cte AS

SELECT row_number() OVER (ORDER BY population DESC) AS pop_rank

, name

, population

FROM country

SELECT *

FROM population_cte pc1

WHERE pop_rank = 1

OR NOT EXISTS (SELECT 1 FROM population_cte pc2 WHERE pc2.pop_rank >


pc1.pop_rank)
89) Create a report that shows all countries that have a rounded population of
100,000,000 or more (rounding to the nearest hundred million). Show the country
name, rounded population, and original population.

Ans=WITH population_cte AS

SELECT name

, ROUND(population, -8) AS pop

, population

FROM country

SELECT *

FROM population_cte pc1

WHERE pop >= 100000000


90) Today we want to test our skills using the CAST() function. Display the name
and population of all countries, except cast the population column so that the
values are all VARCHAR.

Ans=SELECT name

, CAST(population AS varchar(50)) AS population FROM country


91) Time to test the CONVERT() function. Convert the GNP to VARCHAR, and
display it along with each country name.

SELECT name

, CONVERT(VARCHAR(50), GNP) AS GNP

FROM country
92) Find all countries whose cities all have populations above 1,000,000.

SELECT co.name

FROM country co

WHERE NOT EXISTS

(SELECT 1
FROM city ci

WHERE co.code = ci.countrycode

AND ci.population < 1000000)

AND co.population <> 0


93) Find the number of employees per office. Output should include office code,
office city and number of employees

select b.officecode, b.city, count(distinct a.employeenumber)

from employees a

join offices b

on a.officecode = b.officecode

group by b.officecode, b.city


94) Calculate the number of employees in the largest office (office that has the
most employees). Name the output column as "maxemployeecount"

select max(c.employeecount) as maxemployeecount

from (select b.officecode, b.city, count(distinct a.employeenumber) as employeecount

from employees a

join offices b

on a.officecode = b.officecode

group by b.officecode, b.city)C


95) Select all the cities whose population is greater than 1 million. Sort the city
names in alphabetical order.

Select name

from city

where population > 1000000

order by name
96) Find all the managers who were hired after their subordinates. Output should
be named as "managerfirstname", "managerlastname", "managerhiredate",
"employeefirstname", "employeelastname", "employeehiredate".
select a.firstname as managerfirstname, a.lastname as managerlastname, a.hiredate as
managerhiredate,

b.firstname as employeefirstname, b.lastname as employeelastname, b.hiredate as


employeehiredate

from employees a

right join employees b

on a.employeeID = b.reportsto

where a.hiredate > b.hiredate


97) select all the customer names and their total payments whose total payment
are more than 100,000. Name total payments as "totalamount". Sort by total
amount (descending order) and customer name.

select a.customername, sum(b.amount) as totalamount

from customers a

join payments b

on a.customernumber = b.customernumber

group by a.customername

having sum(b.amount) > 100000

order by totalamount desc, a.customername


98) Select the country codes where the country language is English. Sort country
code in alphabetical order.

Select countrycode

from countrylanguage

where upper(language) = 'ENGLISH'

order by countrycode
99) Display product line, product line text description and revenue for each
product line. Sort by revenue in descending order.

select b.productline, b.textdescription, sum(c.quantityordered * c.priceEach) as revenue

from products a

join productlines b
on a.productline = b.productline

join orderdetails c

on c.productcode = a.productcode

group by b.productline, b.textdescription

order by revenue desc


100) Display the product line that has the highest order revenue. Output should
include and be labeled as "productline", "textdescription" and "revenue".

select b.productline, b.textdescription, sum(c.quantityordered * c.priceEach) as revenue

from products a

join orderdetails c

on c.productcode = a.productcode

join productlines b

on a.productline = b.productline

group by b.productline, b.textdescription

having sum(c.quantityordered * c.priceEach) = (select max(D.revenue) as maxrevenue

from (select a.productline, sum(c.quantityordered *


c.priceEach) as revenue

from products a

join orderdetails c

on c.productcode = a.productcode

group by a.productline) D)

101) Find the customer name who has the highest credit limit. If
there is more than one, sort customer names in alphabetical order.

select a.customername, a.creditlimit

from customers a

where a.creditlimit = (select max(creditlimit) from customers)


order by customername

102) Calculate the number of products each supplier is responsible for. Output
should include supplier ID, supplier company name and product count. Sort by
product count (descending) and company name (alphabetic order).

select b.supplierID, b.companyName, count(distinct a.productID) as productcount

from products a

join suppliers b

on a.supplierID = b.supplierID

group by b.supplierID, b.companyName

order by productcount desc, b.companyName

Potrebbero piacerti anche