Input
stringlengths
34
376
Table
stringlengths
11
229
Output
stringlengths
57
1.01k
retrieve all rows and columns from the employee table in the Adventureworks database Sort the result set in ascending order on jobtitle
humanresources.employee
SELECT * FROM humanresources.employee ORDER BY jobtitle;
retrieve all rows and columns from the employee table using table aliasing in the Adventureworks database Sort the output in ascending order on lastname
person.person
SELECT e.* FROM person.person AS e ORDER BY LastName;
return all rows and a subset of the columns (FirstName LastName businessentityid) from the person table in the AdventureWorks database The third column heading is renamed to Employee_id Arranged the output in ascending order by lastname
person.person
SELECT firstname, lastname, businessentityid as Employee_id FROM person.person AS e ORDER BY lastname;
return only the rows for product that have a sellstartdate that is not NULL and a productline of 'T' Return productid productnumber and name Arranged the output in ascending order on name
production.product
SELECT productid, productnumber, name as producName FROM production.product WHERE sellstartdate IS NOT NULL AND production.product.productline= 'T' ORDER BY name;
return all rows from the salesorderheader table in Adventureworks database and calculate the percentage of tax on the subtotal have decided Return salesorderid customerid orderdate subtotal percentage of tax column Arranged the result set in descending order on subtotal
sales.salesorderheader
SELECT salesorderid,customerid,orderdate,subtotal, (taxamt*100)/subtotal AS Tax_percent FROM sales.salesorderheader ORDER BY subtotal desc;
create a list of unique jobtitles in the employee table in Adventureworks database Return jobtitle column and arranged the resultset in ascending order
humanresources.employee
SELECT DISTINCT jobtitle FROM humanresources.employee ORDER BY jobtitle;
calculate the total freight paid by each customer Return customerid and total freight Sort the output in ascending order on customerid
sales.salesorderheader
SELECT customerid,sum(freight) as total_freight FROM sales.salesorderheader group by customerid ORDER BY customerid ASC;
find the average and the sum of the subtotal for every customer Return customerid average and sum of the subtotal Grouped the result on customerid and salespersonid Sort the result on customerid column in descending order
sales.salesorderheader
SELECT customerid,salespersonid,AVG(subtotal) AS avg_subtotal, SUM(subtotal) AS sum_subtotal FROM sales.salesorderheader GROUP BY customerid,salespersonid ORDER BY customerid DESC;
retrieve total quantity of each productid which are in shelf of 'A' or 'C' or 'H' Filter the results for sum quantity is more than 500 Return productid and sum of the quantity Sort the results according to the productid in ascending order
production.productinventory
SELECT productid, sum(quantity) AS total_quantity FROM production.productinventory WHERE shelf IN ('A','C','H') GROUP BY productid HAVING SUM(quantity)>500 ORDER BY productid;
find the total quentity for a group of locationid multiplied by 10
production.productinventory
SELECT SUM(quantity) AS total_quantity FROM production.productinventory GROUP BY (locationid*10);
From the following tables write a query in SQL to find the persons whose last name starts with letter 'L' Return BusinessEntityID FirstName LastName and PhoneNumber Sort the result on lastname and firstname
Person.PersonPhone
SELECT p.BusinessEntityID, FirstName, LastName, PhoneNumber AS Person_Phone FROM Person.Person AS p JOIN Person.PersonPhone AS ph ON p.BusinessEntityID = ph.BusinessEntityID WHERE LastName LIKE 'L%' ORDER BY LastName, FirstName;
find the sum of subtotal column Group the sum on distinct salespersonid and customerid Rolls up the results into subtotal and running total Return salespersonid customerid and sum of subtotal column i e sum_subtotal
sales.salesorderheader
SELECT salespersonid,customerid,sum(subtotal) AS sum_subtotal FROM sales.salesorderheader s GROUP BY ROLLUP (salespersonid, customerid);
find the sum of the quantity of all combination of group of distinct locationid and shelf column Return locationid shelf and sum of quantity as TotalQuantity
production.productinventory
SELECT locationid, shelf, SUM(quantity) AS TotalQuantity FROM production.productinventory GROUP BY CUBE (locationid, shelf);
find the sum of the quantity with subtotal for each locationid Group the results for all combination of distinct locationid and shelf column Rolls up the results into subtotal and running total Return locationid shelf and sum of quantity as TotalQuantity
production.productinventory
SELECT locationid, shelf, SUM(quantity) AS TotalQuantity FROM production.productinventory GROUP BY GROUPING SETS ( ROLLUP (locationid, shelf), CUBE (locationid, shelf) );
find the total quantity for each locationid and calculate the grand-total for all locations Return locationid and total quantity Group the results on locationid
production.productinventory
SELECT locationid, SUM(quantity) AS TotalQuantity FROM production.productinventory GROUP BY GROUPING SETS ( locationid, () );
retrieve the number of employees for each City Return city and number of employees Sort the result in ascending order on city
Person.BusinessEntityAddress
SELECT a.City, COUNT(b.AddressID) NoOfEmployees FROM Person.BusinessEntityAddress AS b INNER JOIN Person.Address AS a ON b.AddressID = a.AddressID GROUP BY a.City ORDER BY a.City;
retrieve the total sales for each year Return the year part of order date and total due amount Sort the result in ascending order on year part of order date
Sales.SalesOrderHeader
SELECT DATE_PART('year',OrderDate) AS "Year" ,SUM(TotalDue) AS "Order Amount" FROM Sales.SalesOrderHeader GROUP BY DATE_PART('year',OrderDate) ORDER BY DATE_PART('year',OrderDate);
retrieve the total sales for each year Filter the result set for those orders where order year is on or before 2016 Return the year part of orderdate and total due amount Sort the result in ascending order on year part of order date
Sales.SalesOrderHeader
SELECT DATE_PART('year',OrderDate) AS YearOfOrderDate ,SUM(TotalDue) AS TotalDueOrder FROM Sales.SalesOrderHeader GROUP BY DATE_PART('year',OrderDate) HAVING DATE_PART('year',OrderDate) <= '2016' ORDER BY DATE_PART('year',OrderDate);
find the contacts who are designated as a manager in various departments Returns ContactTypeID name Sort the result set in descending order
Person.ContactType
SELECT ContactTypeID, Name FROM Person.ContactType WHERE Name LIKE '%Manager%' ORDER BY Name DESC;
From the following tables write a query in SQL to make a list of contacts who are designated as 'Purchasing Manager' Return BusinessEntityID LastName and FirstName columns Sort the result set in ascending order of LastName and FirstName
Person.BusinessEntityContact
SELECT pp.BusinessEntityID, LastName, FirstName FROM Person.BusinessEntityContact AS pb INNER JOIN Person.ContactType AS pc ON pc.ContactTypeID = pb.ContactTypeID INNER JOIN Person.Person AS pp ON pp.BusinessEntityID = pb.PersonID WHERE pc.Name = 'Purchasing Manager' ORDER BY LastName, FirstName;
From the following tables write a query in SQL to retrieve the salesperson for each PostalCode who belongs to a territory and SalesYTD is not zero Return row numbers of each group of PostalCode last name salesytd postalcode column Sort the salesytd of each postalcode group in descending order Shorts the postalcode in ascending order
Sales.SalesPerson
SELECT ROW_NUMBER() OVER win AS "Row Number", pp.LastName, sp.SalesYTD, pa.PostalCode FROM Sales.SalesPerson AS sp INNER JOIN Person.Person AS pp ON sp.BusinessEntityID = pp.BusinessEntityID INNER JOIN Person.Address AS pa ON pa.AddressID = pp.BusinessEntityID WHERE TerritoryID IS NOT NULL AND SalesYTD <> 0 WINDOW win AS (PARTITION BY PostalCode ORDER BY SalesYTD DESC) ORDER BY PostalCode;
count the number of contacts for combination of each type and name Filter the output for those who have 100 or more contacts Return ContactTypeID and ContactTypeName and BusinessEntityContact Sort the result set in descending order on number of contacts
Person.BusinessEntityContact
SELECT pc.ContactTypeID, pc.Name AS CTypeName, COUNT(*) AS NOcontacts FROM Person.BusinessEntityContact AS pbe INNER JOIN Person.ContactType AS pc ON pc.ContactTypeID = pbe.ContactTypeID GROUP BY pc.ContactTypeID, pc.Name HAVING COUNT(*) >= 100 ORDER BY COUNT(*) DESC;
retrieve the RateChangeDate full name (first name middle name and last name) and weekly salary (40 hours in a week) of employees In the output the RateChangeDate should appears in date format Sort the output in ascending order on NameInFull
HumanResources.EmployeePayHistory
SELECT CAST(hur.RateChangeDate as VARCHAR(10) ) AS FromDate , CONCAT(LastName, ', ', FirstName, ' ', MiddleName) AS NameInFull , (40 * hur.Rate) AS SalaryInAWeek FROM Person.Person AS pp INNER JOIN HumanResources.EmployeePayHistory AS hur ON hur.BusinessEntityID = pp.BusinessEntityID ORDER BY NameInFull;
From the following tables write a query in SQL to calculate and display the latest weekly salary of each employee Return RateChangeDate full name (first name middle name and last name) and weekly salary (40 hours in a week) of employees Sort the output in ascending order on NameInFull
Person.Person
SELECT CAST(hur.RateChangeDate as VARCHAR(10) ) AS FromDate , CONCAT(LastName, ', ', FirstName, ' ', MiddleName) AS NameInFull , (40 * hur.Rate) AS SalaryInAWeek FROM Person.Person AS pp INNER JOIN HumanResources.EmployeePayHistory AS hur ON hur.BusinessEntityID = pp.BusinessEntityID WHERE hur.RateChangeDate = (SELECT MAX(RateChangeDate) FROM HumanResources.EmployeePayHistory WHERE BusinessEntityID = hur.BusinessEntityID) ORDER BY NameInFull;
find the sum average count minimum and maximum order quentity for those orders whose id are 43659 and 43664 Return SalesOrderID ProductID OrderQty sum average count max and min order quantity
Sales.SalesOrderDetail
SELECT SalesOrderID, ProductID, OrderQty ,SUM(OrderQty) OVER win AS "Total Quantity" ,AVG(OrderQty) OVER win AS "Avg Quantity" ,COUNT(OrderQty) OVER win AS "No of Orders" ,MIN(OrderQty) OVER win AS "Min Quantity" ,MAX(OrderQty) OVER win AS "Max Quantity" FROM Sales.SalesOrderDetail WHERE SalesOrderID IN(43659,43664) WINDOW win AS (PARTITION BY SalesOrderID);
find the sum average and number of order quantity for those orders whose ids are 43659 and 43664 and product id starting with '71' Return SalesOrderID OrderNumber ProductID OrderQty sum average and number of order quantity
Sales.SalesOrderDetail
SELECT SalesOrderID AS OrderNumber, ProductID, OrderQty AS Quantity, SUM(OrderQty) OVER (ORDER BY SalesOrderID, ProductID) AS Total, AVG(OrderQty) OVER(PARTITION BY SalesOrderID ORDER BY SalesOrderID, ProductID) AS Avg, COUNT(OrderQty) OVER(ORDER BY SalesOrderID, ProductID ROWS BETWEEN UNBOUNDED PRECEDING AND 1 FOLLOWING) AS Count FROM Sales.SalesOrderDetail WHERE SalesOrderID IN(43659,43664) and CAST(ProductID AS TEXT) LIKE '71%';
retrieve the total cost of each salesorderID that exceeds 100000 Return SalesOrderID total cost
Sales.SalesOrderDetail
SELECT SalesOrderID, SUM(orderqty*unitprice) AS OrderIDCost FROM Sales.SalesOrderDetail GROUP BY SalesOrderID HAVING SUM(orderqty*unitprice) > 100000.00 ORDER BY SalesOrderID;
retrieve products whose names start with 'Lock Washer' Return product ID and name and order the result set in ascending order on product ID column
Production.Product
SELECT ProductID, Name FROM Production.Product WHERE Name LIKE 'Lock Washer%' ORDER BY ProductID;
Write a query in SQL to fetch rows from product table and order the result set on an unspecified column listprice Return product ID name and color of the product
Production.Product
SELECT ProductID, Name, Color FROM Production.Product ORDER BY ListPrice;
retrieve records of employees Order the output on year (default ascending order) of hiredate Return BusinessEntityID JobTitle and HireDate
HumanResources.Employee
SELECT BusinessEntityID, JobTitle, HireDate FROM HumanResources.Employee ORDER BY DATE_PART('year',HireDate);
retrieve those persons whose last name begins with letter 'R' Return lastname and firstname and display the result in ascending order on firstname and descending order on lastname columns
Person.Person
SELECT LastName, FirstName FROM Person.Person WHERE LastName LIKE 'R%' ORDER BY FirstName ASC, LastName DESC ;
ordered the BusinessEntityID column descendingly when SalariedFlag set to 'true' and BusinessEntityID in ascending order when SalariedFlag set to 'false' Return BusinessEntityID SalariedFlag columns
HumanResources.Employee
SELECT BusinessEntityID, SalariedFlag FROM HumanResources.Employee ORDER BY CASE SalariedFlag WHEN 'true' THEN BusinessEntityID END DESC ,CASE WHEN SalariedFlag ='false' THEN BusinessEntityID END;
set the result in order by the column TerritoryName when the column CountryRegionName is equal to 'United States' and by CountryRegionName for all other rows
Sales.SalesPerson
SELECT BusinessEntityID, LastName, TerritoryName, CountryRegionName FROM Sales.vSalesPerson WHERE TerritoryName IS NOT NULL ORDER BY CASE CountryRegionName WHEN 'United States' THEN TerritoryName ELSE CountryRegionName END;
find those persons who lives in a territory and the value of salesytd except 0 Return first name last name row number as 'Row Number' 'Rank' 'Dense Rank' and NTILE as 'Quartile' salesytd and postalcode Order the output on postalcode column
Sales.SalesPerson
SELECT p.FirstName, p.LastName ,ROW_NUMBER() OVER (ORDER BY a.PostalCode) AS "Row Number" ,RANK() OVER (ORDER BY a.PostalCode) AS "Rank" ,DENSE_RANK() OVER (ORDER BY a.PostalCode) AS "Dense Rank" ,NTILE(4) OVER (ORDER BY a.PostalCode) AS "Quartile" ,s.SalesYTD, a.PostalCode FROM Sales.SalesPerson AS s INNER JOIN Person.Person AS p ON s.BusinessEntityID = p.BusinessEntityID INNER JOIN Person.Address AS a ON a.AddressID = p.BusinessEntityID WHERE TerritoryID IS NOT NULL AND SalesYTD <> 0;
skip the first 10 rows from the sorted result set and return all remaining rows
HumanResources.Department
SELECT DepartmentID, Name, GroupName FROM HumanResources.Department ORDER BY DepartmentID OFFSET 10 ROWS;
skip the first 5 rows and return the next 5 rows from the sorted result set
HumanResources.Department
SELECT DepartmentID, Name, GroupName FROM HumanResources.Department ORDER BY DepartmentID OFFSET 5 ROWS FETCH NEXT 5 ROWS ONLY;
list all the products that are Red or Blue in color Return name color and listprice Sorts this result by the column listprice
Production.Product
SELECT Name, Color, ListPrice FROM Production.Product WHERE Color = 'Red' UNION ALL SELECT Name, Color, ListPrice FROM Production.Product WHERE Color = 'Blue' ORDER BY ListPrice ASC;
Create a SQL query from the SalesOrderDetail table to retrieve the product name and any associated sales orders Additionally it returns any sales orders that don't have any items mentioned in the Product table as well as any products that have sales orders other than those that are listed there Return product name salesorderid Sort the result set on product name column
Production.Product
SELECT p.Name, sod.SalesOrderID FROM Production.Product AS p FULL OUTER JOIN Sales.SalesOrderDetail AS sod ON p.ProductID = sod.ProductID ORDER BY p.Name ;
From the following table write a SQL query to retrieve the product name and salesorderid Both ordered and unordered products are included in the result set
Production.Product
SELECT p.Name, sod.SalesOrderID FROM Production.Product AS p LEFT OUTER JOIN Sales.SalesOrderDetail AS sod ON p.ProductID = sod.ProductID ORDER BY p.Name ;
From the following tables write a SQL query to get all product names and sales order IDs Order the result set on product name column
Production.Product
SELECT p.Name, sod.SalesOrderID FROM Production.Product AS p INNER JOIN Sales.SalesOrderDetail AS sod ON p.ProductID = sod.ProductID ORDER BY p.Name ;
From the following tables write a SQL query to retrieve the territory name and BusinessEntityID The result set includes all salespeople regardless of whether or not they are assigned a territory
Sales.SalesTerritory
SELECT st.Name AS Territory, sp.BusinessEntityID FROM Sales.SalesTerritory AS st RIGHT OUTER JOIN Sales.SalesPerson AS sp ON st.TerritoryID = sp.TerritoryID ;
Write a query in SQL to find the employee's full name (firstname and lastname) and city from the following tables Order the result set on lastname then by firstname
Person.Person
SELECT concat(RTRIM(p.FirstName),' ', LTRIM(p.LastName)) AS Name, d.City FROM Person.Person AS p INNER JOIN HumanResources.Employee e ON p.BusinessEntityID = e.BusinessEntityID INNER JOIN (SELECT bea.BusinessEntityID, a.City FROM Person.Address AS a INNER JOIN Person.BusinessEntityAddress AS bea ON a.AddressID = bea.AddressID) AS d ON p.BusinessEntityID = d.BusinessEntityID ORDER BY p.LastName, p.FirstName;
Write a SQL query to return the businessentityid firstname and lastname columns of all persons in the person table (derived table) with persontype is 'IN' and the last name is 'Adams' Sort the result set in ascending order on firstname A SELECT statement after the FROM clause is a derived table
Person.Person
SELECT businessentityid, firstname,lastname FROM (SELECT * FROM person.person WHERE persontype = 'IN') AS personDerivedTable WHERE lastname = 'Adams' ORDER BY firstname;
Create a SQL query to retrieve individuals from the following table with a businessentityid inside 1500 a lastname starting with 'Al' and a firstname starting with 'M'
Person.Person
SELECT businessentityid, firstname,LastName FROM person.person WHERE businessentityid <= 1500 AND LastName LIKE '%Al%' AND FirstName LIKE '%M%';
Write a SQL query to find the productid name and colour of the items 'Blade' 'Crown Race' and 'AWC Logo Cap' using a derived table with multiple values
Production.Product
SELECT ProductID, a.Name, Color FROM Production.Product AS a INNER JOIN (VALUES ('Blade'), ('Crown Race'), ('AWC Logo Cap')) AS b(Name) ON a.Name = b.Name;
Create a SQL query to display the total number of sales orders each sales representative receives annually Sort the result set by SalesPersonID and then by the date component of the orderdate in ascending order Return the year component of the OrderDate SalesPersonID and SalesOrderID
Sales.SalesOrderHeader
WITH Sales_CTE (SalesPersonID, SalesOrderID, SalesYear) AS ( SELECT SalesPersonID, SalesOrderID, DATE_PART('year',OrderDate) AS SalesYear FROM Sales.SalesOrderHeader WHERE SalesPersonID IS NOT NULL ) SELECT SalesPersonID, COUNT(SalesOrderID) AS TotalSales, SalesYear FROM Sales_CTE GROUP BY SalesYear, SalesPersonID ORDER BY SalesPersonID, SalesYear;
find the average number of sales orders for all the years of the sales representatives
Sales.SalesOrderHeader
WITH Sales_CTE (SalesPersonID, NumberOfOrders) AS ( SELECT SalesPersonID, COUNT(*) FROM Sales.SalesOrderHeader WHERE SalesPersonID IS NOT NULL GROUP BY SalesPersonID ) SELECT AVG(NumberOfOrders) AS "Average Sales Per Person" FROM Sales_CTE;
Write a SQL query on the following table to retrieve records with the characters green_ in the LargePhotoFileName field The following table's columns must all be returned
Production.ProductPhoto
SELECT * FROM Production.ProductPhoto WHERE LargePhotoFileName LIKE '%greena_%' ESCAPE 'a' ;
Write a SQL query to retrieve the mailing address for any company that is outside the United States (US) and in a city whose name starts with Pa Return Addressline1 Addressline2 city postalcode countryregioncode columns
Person.Address
SELECT AddressLine1, AddressLine2, City, PostalCode, CountryRegionCode FROM Person.Address AS a JOIN Person.StateProvince AS s ON a.StateProvinceID = s.StateProvinceID WHERE CountryRegionCode NOT IN ('US') AND City LIKE 'Pa%' ;
fetch first twenty rows Return jobtitle hiredate Order the result set on hiredate column in descending order
HumanResources.Employee
SELECT JobTitle, HireDate FROM HumanResources.Employee ORDER BY HireDate desc FETCH FIRST 20 ROWS ONLY;
From the following tables write a SQL query to retrieve the orders with orderqtys greater than 5 or unitpricediscount less than 1000 and totaldues greater than 100 Return all the columns from the tables
Sales.SalesOrderHeader
SELECT * FROM Sales.SalesOrderHeader AS h INNER JOIN Sales.SalesOrderDetail AS d ON h.SalesOrderID = d.SalesOrderID WHERE h.TotalDue > 100 AND (d.OrderQty > 5 OR d.unitpricediscount < 1000.00);
From the following table write a query in SQL that searches for the word 'red' in the name column Return name and color columns from the table
Production.Product
SELECT Name, Color FROM Production.Product WHERE to_tsvector(name) @@ to_tsquery('red');
find all the products with a price of $80 99 that contain the word Mountain Return name and listprice columns from the table
Production.Product
SELECT Name, ListPrice FROM Production.Product WHERE ListPrice = 80.99 and to_tsvector(name) @@ to_tsquery('Mountain');
retrieve all the products that contain either the phrase Mountain or Road Return name and color columns
Production.Product
SELECT Name,color FROM Production.Product WHERE to_tsvector(name) @@ to_tsquery('Mountain | Road');
search for name which contains both the word 'Mountain' and the word 'Black' Return Name and color
Production.Product
SELECT Name,color FROM Production.Product WHERE to_tsvector(name) @@ to_tsquery('Mountain & Black');
return all the product names with at least one word starting with the prefix chain in the Name column
Production.Product
SELECT Name,color FROM Production.Product WHERE to_tsvector(name) @@ to_tsquery(' "Chain*" ');
return all category descriptions containing strings with prefixes of either chain or full
Production.Product
SELECT Name, color FROM Production.Product WHERE to_tsvector(name) @@ to_tsquery('"chain*" | "full*"');
From the following table write a SQL query to output an employee's name and email address separated by a new line character
Person.Person
SELECT concat(p.FirstName,' ', p.LastName) || ' '|| chr(10)|| pe.EmailAddress FROM Person.Person p INNER JOIN Person.EmailAddress pe ON p.BusinessEntityID = pe.BusinessEntityID AND p.BusinessEntityID = 1;
From the following table write a SQL query to locate the position of the string "yellow" where it appears in the product name
production.product
SELECT name, strpos(name,'Yellow') as "String Position" from production.product where strpos(name,'Yellow')>0;
concatenate the name color and productnumber columns
production.product
SELECT CONCAT( name, ' color:-',color,' Product Number:', productnumber ) AS result, color FROM production.product;
Write a SQL query that concatenate the columns name productnumber colour and a new line character from the following table each separated by a specified character
production.product
SELECT CONCAT_WS( ',', name, productnumber, color,chr(10)) AS DatabaseInfo FROM production.product;
return the five leftmost characters of each product name
production.product
SELECT LEFT(Name, 5) FROM Production.Product ORDER BY ProductID;
select the number of characters and the data in FirstName for people located in Australia
Sales.vindividualcustomer
SELECT LENgth(FirstName) AS Length, FirstName, LastName FROM Sales.vIndividualCustomer WHERE CountryRegionName = 'Australia';
From the following tables write a query in SQL to return the number of characters in the column FirstName and the first and last name of contacts located in Australia
Sales.vstorewithcontacts
SELECT DISTINCT LENgth(FirstName) AS FNameLength, FirstName, LastName FROM Sales.vstorewithcontacts AS e INNER JOIN Sales.vstorewithaddresses AS g ON e.businessentityid = g.businessentityid WHERE CountryRegionName = 'Australia';
select product names that have prices between $1000 00 and $1220 00 Return product name as Lower Upper and also LowerUpper
production.Product
SELECT LOWER(SUBSTRING(Name, 1, 25)) AS Lower, UPPER(SUBSTRING(Name, 1, 25)) AS Upper, LOWER(UPPER(SUBSTRING(Name, 1, 25))) As LowerUpper FROM production.Product WHERE standardcost between 1000.00 and 1220.00;
Write a query in SQL to remove the spaces from the beginning of a string
Sample Solution
SELECT ' five space then the text' as "Original Text", LTRIM(' five space then the text') as "Trimmed Text(space removed)";
remove the substring 'HN' from the start of the column productnumber Filter the results to only show those productnumbers that start with "HN" Return original productnumber column and 'TrimmedProductnumber'
production.Product
SELECT productnumber,LTRIM(productnumber , 'HN') as "TrimmedProductnumber" from production.product where left(productnumber,2)='HN';
repeat a 0 character four times in front of a production line for production line 'T'
production.Product
SELECT Name, concat(REPeat('0', 4) , ProductLine) AS "Line Code" FROM Production.Product WHERE ProductLine = 'T' ORDER BY Name;
From the following table write a SQL query to retrieve all contact first names with the characters inverted for people whose businessentityid is less than 6
Person.Person
SELECT FirstName, REVERSE(FirstName) AS Reverse FROM Person.Person WHERE BusinessEntityID < 6 ORDER BY FirstName;
return the eight rightmost characters of each name of the product Also return name productnumber column Sort the result set in ascending order on productnumber
production.Product
SELECT name, productnumber, RIGHT(name, 8) AS "Product Name" FROM production.product ORDER BY productnumber;
Write a query in SQL to remove the spaces at the end of a string
Sample Solution
SELECT CONCAT('text then five spaces ','after space') as "Original Text", CONCAT(RTRIM('text then five spaces '),'after space') as "Trimmed Text(space removed)";
fetch the rows for the product name ends with the letter 'S' or 'M' or 'L' Return productnumber and name
production.Product
SELECT productnumber, name FROM production.product WHERE RIGHT(name,1) in ('S','M','L');
replace null values with 'N/A' and return the names separated by commas in a single row
Person.Person
SELECT STRING_AGG(coalesce(firstname, ' N/A'),', ') AS test FROM Person.Person;
return the names and modified date separated by commas in a single row
Person.Person
SELECT STRING_AGG(CONCAT(FirstName, ' ', LastName, ' (', ModifiedDate, ')'),', ') AS test FROM Person.Person;
find the email addresses of employees and groups them by city Return top ten rows
Person.BusinessEntityAddress
SELECT City, STRING_AGG(cast(EmailAddress as varchar(10485760)), ';') AS emails FROM Person.BusinessEntityAddress AS BEA INNER JOIN Person.Address AS A ON BEA.AddressID = A.AddressID INNER JOIN Person.EmailAddress AS EA ON BEA.BusinessEntityID = EA.BusinessEntityID GROUP BY City limit 10;
create a new job title called "Production Assistant" in place of "Production Supervisor"
HumanResources.Employee
SELECT jobtitle, overlay(jobtitle placing 'Assistant' FROM 12 for 10) as "New Jobtitle" FROM humanresources.employee e WHERE SUBSTR(jobtitle,12,10)='Supervisor';
From the following table write a SQL query to retrieve all the employees whose job titles begin with "Sales" Return firstname middlename lastname and jobtitle column
Person.Person
SELECT pepe.firstname, pepe.middlename, pepe.lastname, huem.jobtitle FROM person.person pepe INNER JOIN humanresources.employee huem ON pepe.businessentityid=huem.businessentityid WHERE SUBSTRING(huem.jobtitle,1,5)='Sales';
return the last name of people so that it is in uppercase trimmed and concatenated with the first name
Person.Person
SELECT CONCAT(UPPER(RTRIM(LastName)) , ', ' , FirstName) AS Name FROM person.person ORDER BY LastName;
show a resulting expression that is too small to display Return FirstName LastName Title and SickLeaveHours The SickLeaveHours will be shown as a small expression in text format
HumanResources.Employee
SELECT p.FirstName, p.LastName, SUBSTRING(p.Title, 1, 25) AS Title, CAST(e.SickLeaveHours AS char(1)) AS "Sick Leave" FROM HumanResources.Employee e JOIN Person.Person p ON e.BusinessEntityID = p.BusinessEntityID WHERE NOT e.BusinessEntityID > 5;
retrieve the name of the products Product that have 33 as the first two digits of listprice
production.Product
SELECT SUBSTRING(Name, 1, 30) AS ProductName, ListPrice FROM Production.Product WHERE CAST(ListPrice AS char(2)) LIKE '33%';
calculate by dividing the total year-to-date sales (SalesYTD) by the commission percentage (CommissionPCT) Return SalesYTD CommissionPCT and the value rounded to the nearest whole number
Sales.SalesPerson
SELECT SalesYTD,CommissionPCT,CAST(ROUND(SalesYTD/CommissionPCT, 0) AS INT) AS Computed FROM Sales.SalesPerson WHERE CommissionPCT != 0;
find those persons that have a 2 in the first digit of their SalesYTD Convert the SalesYTD column to an int type and then to a char(20) type Return FirstName LastName SalesYTD and BusinessEntityID
Person.Person
SELECT p.FirstName, p.LastName, s.SalesYTD, s.BusinessEntityID FROM Person.Person AS p JOIN Sales.SalesPerson AS s ON p.BusinessEntityID = s.BusinessEntityID WHERE CAST(CAST(s.SalesYTD AS INT) AS char(20)) LIKE '2%';
convert the Name column to a char(16) column Convert those rows if the name starts with 'Long-Sleeve Logo Jersey' Return name of the product and listprice
production.Product
SELECT CAST(Name AS CHAR(16)) AS Name, ListPrice FROM production.Product WHERE Name LIKE 'Long-Sleeve Logo Jersey%';
From the following table write a SQL query to determine the discount price for the salesorderid 46672 Calculate only those orders with discounts of more than 02 percent Return productid UnitPrice UnitPriceDiscount and DiscountPrice (UnitPrice*UnitPriceDiscount )
Sales.SalesOrderDetail
SELECT productid, UnitPrice,UnitPriceDiscount, CAST(ROUND (UnitPrice*UnitPriceDiscount,0) AS int) AS DiscountPrice FROM sales.salesorderdetail WHERE SalesOrderid = 46672 AND UnitPriceDiscount > .02;
calculate the average vacation hours and the sum of sick leave hours that the vice presidents have used
HumanResources.Employee
SELECT AVG(VacationHours)AS "Average vacation hours", SUM(SickLeaveHours) AS "Total sick leave hours" FROM HumanResources.Employee WHERE JobTitle LIKE 'Vice President%';
calculate the average bonus received and the sum of year-to-date sales for each territory Return territoryid Average bonus and YTD sales
Sales.SalesPerson
SELECT TerritoryID, AVG(Bonus)as "Average bonus", SUM(SalesYTD) as "YTD sales" FROM Sales.SalesPerson GROUP BY TerritoryID;
return the average list price of products Consider the calculation only on unique values
production.Product
SELECT AVG(DISTINCT ListPrice) FROM Production.Product;
return a moving average of yearly sales for each territory Return BusinessEntityID TerritoryID SalesYear SalesYTD average SalesYTD as MovingAvg and total SalesYTD as CumulativeTotal
Sales.SalesPerson
SELECT BusinessEntityID, TerritoryID ,DATE_PART('year',ModifiedDate) AS SalesYear ,cast(SalesYTD as VARCHAR(20)) AS SalesYTD ,AVG(SalesYTD) OVER (PARTITION BY TerritoryID ORDER BY DATE_PART('year',ModifiedDate)) AS MovingAvg ,SUM(SalesYTD) OVER (PARTITION BY TerritoryID ORDER BY DATE_PART('year',ModifiedDate)) AS CumulativeTotal FROM Sales.SalesPerson WHERE TerritoryID IS NULL OR TerritoryID < 5 ORDER BY TerritoryID,SalesYear;
return a moving average of sales by year for all sales territories Return BusinessEntityID TerritoryID SalesYear SalesYTD average SalesYTD as MovingAvg and total SalesYTD as CumulativeTotal
Sales.SalesPerson
SELECT BusinessEntityID, TerritoryID ,DATE_PART('year',ModifiedDate) AS SalesYear ,cast(SalesYTD as VARCHAR(20)) AS SalesYTD ,AVG(SalesYTD) OVER (ORDER BY DATE_PART('year',ModifiedDate)) AS MovingAvg ,SUM(SalesYTD) OVER (ORDER BY DATE_PART('year',ModifiedDate)) AS CumulativeTotal FROM Sales.SalesPerson WHERE TerritoryID IS NULL OR TerritoryID < 5 ORDER BY SalesYear;
return the number of different titles that employees can hold
HumanResources.Employee
SELECT COUNT(DISTINCT jobTitle) as "Number of Jobtitles" FROM HumanResources.Employee;
find the total number of employees
HumanResources.Employee
SELECT COUNT(*) as "Number of Employees" FROM HumanResources.Employee;
find the average bonus for the salespersons who achieved the sales quota above 25000 Return number of salespersons and average bonus
Sales.SalesPerson
SELECT COUNT(*), AVG(Bonus) FROM Sales.SalesPerson WHERE SalesQuota > 25000;
From the following tables wirte a query in SQL to return aggregated values for each department Return name minimum salary maximum salary average salary and number of employees in each department
HumanResources.employeepayhistory
SELECT DISTINCT Name , MIN(Rate) OVER (PARTITION BY edh.DepartmentID) AS MinSalary , MAX(Rate) OVER (PARTITION BY edh.DepartmentID) AS MaxSalary , AVG(Rate) OVER (PARTITION BY edh.DepartmentID) AS AvgSalary ,COUNT(edh.BusinessEntityID) OVER (PARTITION BY edh.DepartmentID) AS EmployeesPerDept FROM HumanResources.EmployeePayHistory AS eph JOIN HumanResources.EmployeeDepartmentHistory AS edh ON eph.BusinessEntityID = edh.BusinessEntityID JOIN HumanResources.Department AS d ON d.DepartmentID = edh.DepartmentID WHERE edh.EndDate IS NULL ORDER BY Name;
From the following tables write a SQL query to return the departments of a company that each have more than 15 employees
humanresources.employee
SELECT jobtitle, COUNT(businessentityid) AS EmployeesInDesig FROM humanresources.employee e GROUP BY jobtitle HAVING COUNT(businessentityid) > 15;
find the number of products that ordered in each of the specified sales orders
Sales.SalesOrderDetail
SELECT DISTINCT COUNT(Productid) OVER(PARTITION BY SalesOrderid) AS ProductCount ,SalesOrderid FROM sales.salesorderdetail WHERE SalesOrderid IN (45363,45365);
compute the statistical variance of the sales quota values for each quarter in a calendar year for a sales person Return year quarter salesquota and variance of salesquota
sales.salespersonquotahistory
SELECT quotadate AS Year, date_part('quarter',quotadate) AS Quarter, SalesQuota AS SalesQuota, variance(SalesQuota) OVER (ORDER BY date_part('year',quotadate), date_part('quarter',quotadate)) AS Variance FROM sales.salespersonquotahistory WHERE businessentityid = 277 AND date_part('year',quotadate) = 2012 ORDER BY date_part('quarter',quotadate);
populate the variance of all unique values as well as all values including any duplicates values of SalesQuota column
sales.salespersonquotahistory
SELECT var_pop(DISTINCT SalesQuota) AS Distinct_Values, var_pop(SalesQuota) AS All_Values FROM sales.salespersonquotahistory;
return the total ListPrice and StandardCost of products for each color Products that name starts with 'Mountain' and ListPrice is more than zero Return Color total list price total standardcode Sort the result set on color in ascending order
production.Product
SELECT Color, SUM(ListPrice), SUM(StandardCost) FROM Production.Product WHERE Color IS NOT NULL AND ListPrice != 0.00 AND Name LIKE 'Mountain%' GROUP BY Color ORDER BY Color;
find the TotalSalesYTD of each SalesQuota Show the summary of the TotalSalesYTD amounts for all SalesQuota groups Return SalesQuota and TotalSalesYTD
Sales.SalesPerson
SELECT SalesQuota, SUM(SalesYTD) as "TotalSalesYTD" , GROUPING(SalesQuota) as "Grouping" FROM Sales.SalesPerson GROUP BY rollup(SalesQuota);
calculate the sum of the ListPrice and StandardCost for each color Return color sum of ListPrice
production.Product
SELECT Color, SUM(ListPrice)AS TotalList, SUM(StandardCost) AS TotalCost FROM production.product GROUP BY Color ORDER BY Color;