Input,Table,Output 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;" calculate the salary percentile for each employee within a given department Return department last name rate cumulative distribution and percent rank of rate Order the result set by ascending on department and descending on rate,HumanResources.vemployeedepartmenthistory,"SELECT Department, LastName, Rate, CUME_DIST () OVER (PARTITION BY Department ORDER BY Rate) AS CumeDist, PERCENT_RANK() OVER (PARTITION BY Department ORDER BY Rate ) AS PctRank FROM HumanResources.vEmployeeDepartmentHistory AS edh INNER JOIN HumanResources.EmployeePayHistory AS e ON e.BusinessEntityID = edh.BusinessEntityID WHERE Department IN ('Information Services','Document Control') ORDER BY Department, Rate DESC;" return the name of the product that is the least expensive in a given product category Return name list price and the first value i e LeastExpensive of the product,production.Product,"SELECT Name, ListPrice, FIRST_VALUE(Name) OVER (ORDER BY ListPrice ASC) AS LeastExpensive FROM Production.Product WHERE ProductSubcategoryID = 37;" return the employee with the fewest number of vacation hours compared to other employees with the same job title Partitions the employees by job title and apply the first value to each partition independently,HumanResources.Employee,"SELECT JobTitle, LastName, VacationHours, FIRST_VALUE(LastName) OVER (PARTITION BY JobTitle ORDER BY VacationHours ASC ROWS UNBOUNDED PRECEDING ) AS FewestVacationHours FROM HumanResources.Employee AS e INNER JOIN Person.Person AS p ON e.BusinessEntityID = p.BusinessEntityID ORDER BY JobTitle;" return the difference in sales quotas for a specific employee over previous years Returun BusinessEntityID sales year current quota and previous quota,Sales.SalesPersonQuotaHistory,"SELECT BusinessEntityID, date_part('year',QuotaDate) AS SalesYear, SalesQuota AS CurrentQuota, LAG(SalesQuota, 1,0) OVER (ORDER BY date_part('year',QuotaDate)) AS PreviousQuota FROM Sales.SalesPersonQuotaHistory WHERE BusinessEntityID = 275 AND date_part('year',QuotaDate) in (2012,2013);" compare year-to-date sales between employees Return TerritoryName BusinessEntityID SalesYTD and sales of previous year i e PrevRepSales Sort the result set in ascending order on territory name,Sales.vSalesPerson,"SELECT TerritoryName, BusinessEntityID, SalesYTD, LAG (SalesYTD, 1, 0) OVER (PARTITION BY TerritoryName ORDER BY SalesYTD DESC) AS PrevRepSales FROM Sales.vSalesPerson WHERE TerritoryName IN ('Northwest', 'Canada') ORDER BY TerritoryName;" From the following tables write a query in SQL to return the hire date of the last employee in each department for the given salary (Rate) Return department lastname rate hiredate and the last value of hiredate,HumanResources.vEmployeeDepartmentHistory,"SELECT Department , LastName , Rate , HireDate , LAST_VALUE(HireDate) OVER ( PARTITION BY Department ORDER BY Rate ) AS LastValue FROM HumanResources.vEmployeeDepartmentHistory AS edh INNER JOIN HumanResources.EmployeePayHistory AS eph ON eph.BusinessEntityID = edh.BusinessEntityID INNER JOIN HumanResources.Employee AS e ON e.BusinessEntityID = edh.BusinessEntityID WHERE Department IN ('Information Services', 'Document Control');" compute the difference between the sales quota value for the current quarter and the first and last quarter of the year respectively for a given number of employees Return BusinessEntityID quarter year differences between current quarter and first and last quarter Sort the result set on BusinessEntityID SalesYear and Quarter in ascending order,Sales.SalesPersonQuotaHistory,"SELECT BusinessEntityID , DATE_PART('quarter', QuotaDate) AS Quarter , date_part('year',QuotaDate) AS SalesYear , SalesQuota AS QuotaThisQuarter , SalesQuota - FIRST_VALUE(SalesQuota) OVER (PARTITION BY BusinessEntityID, date_part('year',QuotaDate) ORDER BY DATE_PART('quarter', QuotaDate)) AS DifferenceFromFirstQuarter , SalesQuota - LAST_VALUE(SalesQuota) OVER (PARTITION BY BusinessEntityID, date_part('year',QuotaDate) ORDER BY DATE_PART('quarter', QuotaDate) RANGE BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) AS DifferenceFromLastQuarter FROM Sales.SalesPersonQuotaHistory WHERE date_part('year',QuotaDate) > 2005 AND BusinessEntityID BETWEEN 274 AND 275 ORDER BY BusinessEntityID, SalesYear, Quarter;" return the statistical variance of the sales quota values for a salesperson for each quarter in a calendar year Return quotadate quarter SalesQuota and statistical variance Order the result set in ascending order on quarter,Sales.SalesPersonQuotaHistory,"SELECT quotadate AS Year, date_part('quarter',quotadate) AS Quarter, SalesQuota AS SalesQuota, var_pop(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);" return the difference in sales quotas for a specific employee over subsequent years Return BusinessEntityID year SalesQuota and the salesquota coming in next row,Sales.SalesPersonQuotaHistory,"SELECT BusinessEntityID, date_part('year',QuotaDate) AS SalesYear, SalesQuota AS CurrentQuota, LEAD(SalesQuota, 1,0) OVER (ORDER BY date_part('year',QuotaDate)) AS NextQuota FROM Sales.SalesPersonQuotaHistory WHERE BusinessEntityID = 277 AND date_part('year',QuotaDate) IN ('2011','2012');" From the following query write a query in SQL to compare year-to-date sales between employees for specific terrotery Return TerritoryName BusinessEntityID SalesYTD and the salesquota coming in next row,Sales.vSalesPerson,"SELECT TerritoryName, BusinessEntityID, SalesYTD, LEAD (SalesYTD, 1, 0) OVER (PARTITION BY TerritoryName ORDER BY SalesYTD DESC) AS NextRepSales FROM Sales.vSalesPerson WHERE TerritoryName IN ('Northwest', 'Canada') ORDER BY TerritoryName;" obtain the difference in sales quota values for a specified employee over subsequent calendar quarters Return year quarter sales quota next sales quota and the difference in sales quota Sort the result set on year and then by quarter both in ascending order,Sales.SalesPersonQuotaHistory,"SELECT date_part('year',quotadate) AS Year, date_part('quarter',quotadate) AS Quarter, SalesQuota AS SalesQuota, LEAD(SalesQuota,1,0) OVER (ORDER BY date_part('year',quotadate), date_part('quarter',quotadate)) AS NextQuota, SalesQuota - LEAD(SalesQuota,1,0) OVER (ORDER BY date_part('year',quotadate), date_part('quarter',quotadate)) AS Diff FROM sales.salespersonquotahistory WHERE businessentityid = 277 AND date_part('year',quotadate) IN (2012,2013) ORDER BY date_part('year',quotadate), date_part('quarter',quotadate);" compute the salary percentile for each employee within a given department Return Department LastName Rate CumeDist and percentile rank Sort the result set in ascending order on department and descending order on rate,"N.B. The cumulative distribution calculates the relative position of a specified value in a group of values.","SELECT Department, LastName, Rate, CUME_DIST () OVER (PARTITION BY Department ORDER BY Rate) AS CumeDist, PERCENT_RANK() OVER (PARTITION BY Department ORDER BY Rate ) AS PctRank FROM HumanResources.vEmployeeDepartmentHistory AS edh INNER JOIN HumanResources.EmployeePayHistory AS e ON e.BusinessEntityID = edh.BusinessEntityID WHERE Department IN ('Information Services','Document Control') ORDER BY Department, Rate DESC;" add two days to each value in the OrderDate column to derive a new column named PromisedShipDate Return salesorderid orderdate and promisedshipdate column,sales.salesorderheader,"SELECT SalesOrderID ,OrderDate ,OrderDate + INTERVAL '2 day' AS PromisedShipDate FROM Sales.SalesOrderHeader;" obtain a newdate by adding two days with current date for each salespersons Filter the result set for those salespersons whose sales value is more than zero,Sales.SalesPerson,"SELECT p.FirstName, p.LastName ,(now() + INTERVAL '2 day') AS ""New Date"" 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;" find the differences between the maximum and minimum orderdate,Sales.SalesOrderHeader,SELECT max(OrderDate) - min(OrderDate) FROM Sales.SalesOrderHeader; rank the products in inventory by the specified inventory locations according to their quantities Divide the result set by LocationID and sort the result set on Quantity in descending order,Production.ProductInventory,"SELECT i.ProductID, p.Name, i.LocationID, i.Quantity ,DENSE_RANK() OVER (PARTITION BY i.LocationID ORDER BY i.Quantity DESC) AS Rank FROM Production.ProductInventory AS i INNER JOIN Production.Product AS p ON i.ProductID = p.ProductID WHERE i.LocationID BETWEEN 3 AND 4 ORDER BY i.LocationID;" return the top ten employees ranked by their salary,HumanResources.EmployeePayHistory,"SELECT BusinessEntityID, Rate, DENSE_RANK() OVER (ORDER BY Rate DESC) AS RankBySalary FROM HumanResources.EmployeePayHistory FETCH FIRST 10 ROWS ONLY;" divide rows into four groups of employees based on their year-to-date sales Return first name last name group as quartile year-to-date sales and postal code,Sales.SalesPerson,"SELECT p.FirstName, p.LastName ,NTILE(4) OVER(ORDER BY SalesYTD DESC) AS Quartile ,CAST(SalesYTD as VARCHAR(20) ) AS 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;" From the following tables write a query in SQL to rank the products in inventory the specified inventory locations according to their quantities The result set is partitioned by LocationID and logically ordered by Quantity Return productid name locationid quantity and rank,production.productinventory,"SELECT i.ProductID, p.Name, i.LocationID, i.Quantity ,RANK() OVER (PARTITION BY i.LocationID ORDER BY i.Quantity DESC) AS Rank FROM Production.ProductInventory AS i INNER JOIN Production.Product AS p ON i.ProductID = p.ProductID WHERE i.LocationID BETWEEN 3 AND 4 ORDER BY i.LocationID;" find the salary of top ten employees Return BusinessEntityID Rate and rank of employees by salary,HumanResources.EmployeePayHistory,"SELECT BusinessEntityID, Rate, RANK() OVER (ORDER BY Rate DESC) AS RankBySalary FROM HumanResources.EmployeePayHistory AS eph1 WHERE RateChangeDate = (SELECT MAX(RateChangeDate) FROM HumanResources.EmployeePayHistory AS eph2 WHERE eph1.BusinessEntityID = eph2.BusinessEntityID) ORDER BY BusinessEntityID FETCH FIRST 10 ROWS ONLY;" calculate a row number for the salespeople based on their year-to-date sales ranking Return row number first name last name and year-to-date sales,Sales.vSalesPerson,"SELECT ROW_NUMBER() OVER(ORDER BY SalesYTD DESC) AS Row, FirstName, LastName, ROUND(SalesYTD,2) AS ""Sales YTD"" FROM Sales.vSalesPerson WHERE TerritoryName IS NOT NULL AND SalesYTD <> 0;" calculate row numbers for all rows between 50 to 60 inclusive Sort the result set on orderdate,Sales.SalesOrderHeader,"WITH OrderedOrders AS ( SELECT SalesOrderID, OrderDate, ROW_NUMBER() OVER (ORDER BY OrderDate) AS RowNumber FROM Sales.SalesOrderHeader ) SELECT SalesOrderID, OrderDate, RowNumber FROM OrderedOrders WHERE RowNumber BETWEEN 50 AND 60;" return first name last name territoryname salesytd and row number Partition the query result set by the TerritoryName Orders the rows in each partition by SalesYTD Sort the result set on territoryname in ascending order,Sales.vSalesPerson,"SELECT FirstName, LastName, TerritoryName, ROUND(SalesYTD,2) AS SalesYTD, ROW_NUMBER() OVER(PARTITION BY TerritoryName ORDER BY SalesYTD DESC) AS Row FROM Sales.vSalesPerson WHERE TerritoryName IS NOT NULL AND SalesYTD <> 0 ORDER BY TerritoryName;" order the result set by the column TerritoryName when the column CountryRegionName is equal to 'United States' and by CountryRegionName for all other rows Return BusinessEntityID LastName TerritoryName CountryRegionName,Sales.vSalesPerson,"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;" From the following tables write a query in SQL to return the highest hourly wage for each job title Restricts the titles to those that are held by men with a maximum pay rate greater than 40 dollars or women with a maximum pay rate greater than 42 dollars,HumanResources.Employee,"SELECT JobTitle, MAX(ph1.Rate)AS MaximumRate FROM HumanResources.Employee AS e JOIN HumanResources.EmployeePayHistory AS ph1 ON e.BusinessEntityID = ph1.BusinessEntityID GROUP BY JobTitle HAVING (MAX(CASE WHEN Gender = 'M' THEN ph1.Rate ELSE NULL END) > 40.00 OR MAX(CASE WHEN Gender = 'F' THEN ph1.Rate ELSE NULL END) > 42.00) ORDER BY MaximumRate DESC;" sort the BusinessEntityID in descending order for those employees that have the SalariedFlag set to 'true' and in ascending order that have the SalariedFlag set to 'false' Return BusinessEntityID and SalariedFlag,HumanResources.Employee,"SELECT BusinessEntityID, SalariedFlag FROM HumanResources.Employee ORDER BY CASE when SalariedFlag = 'true' THEN BusinessEntityID END DESC ,CASE WHEN SalariedFlag = 'false' THEN BusinessEntityID END;" display the list price as a text comment based on the price range for a product Return ProductNumber Name and listprice Sort the result set on ProductNumber in ascending order,production.Product,"SELECT ProductNumber, Name, listprice, CASE WHEN ListPrice = 0 THEN 'Mfg item - not for resale' WHEN ListPrice < 50 THEN 'Under $50' WHEN ListPrice >= 50 and ListPrice < 250 THEN 'Under $250' WHEN ListPrice >= 250 and ListPrice < 1000 THEN 'Under $1000' ELSE 'Over $1000' END ""Price Range"" FROM Production.Product ORDER BY ProductNumber ;" change the display of product line categories to make them more understandable Return ProductNumber category and name of the product Sort the result set in ascending order on ProductNumber,production.Product,"SELECT ProductNumber, CASE ProductLine WHEN 'R' THEN 'Road' WHEN 'M' THEN 'Mountain' WHEN 'T' THEN 'Touring' WHEN 'S' THEN 'Other sale items' ELSE 'Not for sale' end ""Category"", Name FROM Production.Product ORDER BY ProductNumber;" evaluate whether the values in the MakeFlag and FinishedGoodsFlag columns are the same,production.Product,"SELECT ProductID, MakeFlag, FinishedGoodsFlag, CASE WHEN MakeFlag = FinishedGoodsFlag THEN NULL ELSE MakeFlag END FROM Production.Product WHERE ProductID < 10;" select the data from the first column that has a nonnull value Retrun Name Class Color ProductNumber and FirstNotNull,production.Product,"SELECT Name, Class, Color, ProductNumber, COALESCE(Class, Color, ProductNumber) AS FirstNotNull FROM Production.Product;" check the values of MakeFlag and FinishedGoodsFlag columns and return whether they are same or not Return ProductID MakeFlag FinishedGoodsFlag and the column that are null or not null,production.Product,"SELECT ProductID, MakeFlag, FinishedGoodsFlag, NULLIF(MakeFlag,FinishedGoodsFlag) AS ""Null if Equal"" FROM Production.Product WHERE ProductID < 10;" From the following tables write a query in SQL to return any distinct values that are returned by both the query,production.Product,SELECT ProductID FROM Production.Product INTERSECT SELECT ProductID FROM Production.WorkOrder ; From the following tables write a query in SQL to return any distinct values from first query that aren't also found on the 2nd query,production.Product,SELECT ProductID FROM Production.Product EXCEPT SELECT ProductID FROM Production.WorkOrder ; From the following tables write a query in SQL to fetch any distinct values from the left query that aren't also present in the query to the right,production.Product,SELECT ProductID FROM Production.WorkOrder EXCEPT SELECT ProductID FROM Production.Product ; From the following tables write a query in SQL to fetch distinct businessentityid that are returned by both the specified query Sort the result set by ascending order on businessentityid,Person.BusinessEntity,SELECT businessentityid FROM person.businessentity INTERSECT SELECT businessentityid FROM person.person WHERE person.persontype = 'IN' ORDER BY businessentityid; From the following table write a query which is the combination of two queries Return any distinct businessentityid from the 1st query that aren't also found in the 2nd query Sort the result set in ascending order on businessentityid,Person.BusinessEntity,SELECT businessentityid FROM person.businessentity except SELECT businessentityid FROM person.person WHERE person.persontype = 'IN' ORDER BY businessentityid; From the following tables write a query in SQL to combine the ProductModelID and Name columns A result set includes columns for productid 3 and 4 Sort the results by name ascending,Production.ProductModel,"SELECT ProductID, Name FROM Production.Product WHERE ProductID NOT IN (3, 4) UNION SELECT ProductModelID, Name FROM Production.ProductModel ORDER BY Name;" find a total number of hours away from work can be calculated by adding vacation time and sick leave Sort results ascending by Total Hours Away,HumanResources.Employee,"SELECT p.FirstName, p.LastName, VacationHours, SickLeaveHours, VacationHours + SickLeaveHours AS ""Total Hours Away"" FROM HumanResources.Employee AS e JOIN Person.Person AS p ON e.BusinessEntityID = p.BusinessEntityID ORDER BY ""Total Hours Away"" ASC;" calculate the tax difference between the highest and lowest tax-rate state or province,Sales.SalesTaxRate,"SELECT MAX(TaxRate) - MIN(TaxRate) AS ""Tax Rate Difference"" FROM Sales.SalesTaxRate WHERE StateProvinceID IS NOT NULL;" From the following tables write a query in SQL to calculate sales targets per month for salespeople,Sales.SalesPerson,"SELECT s.BusinessEntityID AS SalesPersonID, FirstName, LastName, SalesQuota, SalesQuota/12 AS ""Sales Target Per Month"" FROM Sales.SalesPerson AS s JOIN HumanResources.Employee AS e ON s.BusinessEntityID = e.BusinessEntityID JOIN Person.Person AS p ON e.BusinessEntityID = p.BusinessEntityID;" return the ID number unit price and the modulus (remainder) of dividing product prices Convert the modulo to an integer value,Sales.SalesOrderDetail,"SELECT ProductID, UnitPrice, OrderQty, CAST(UnitPrice AS INT) % OrderQty AS Modulo FROM Sales.SalesOrderDetail;" select employees who have the title of Marketing Assistant and more than 41 vacation hours,HumanResources.Employee,"SELECT BusinessEntityID, LoginID, JobTitle, VacationHours FROM HumanResources.Employee WHERE JobTitle = 'Marketing Assistant' AND VacationHours > 41 ;" From the following tables write a query in SQL to find all rows outside a specified range of rate between 27 and 30 Sort the result in ascending order on rate,HumanResources.vEmployee,"SELECT e.FirstName, e.LastName, ep.Rate FROM HumanResources.vEmployee e JOIN HumanResources.EmployeePayHistory ep ON e.BusinessEntityID = ep.BusinessEntityID WHERE ep.Rate NOT BETWEEN 27 AND 30 ORDER BY ep.Rate;" From the follwing table write a query in SQL to retrieve rows whose datetime values are between '20111212' and '20120105',HumanResources.EmployeePayHistory,"SELECT BusinessEntityID, RateChangeDate FROM HumanResources.EmployeePayHistory WHERE RateChangeDate BETWEEN '20111212' AND '20120105';" return TRUE even if NULL is specified in the subquery Return DepartmentID Name and sort the result set in ascending order,HumanResources.Department,"SELECT DepartmentID, Name FROM HumanResources.Department WHERE EXISTS (SELECT NULL) ORDER BY Name ASC ;" From the following tables write a query in SQL to get employees with Johnson last names Return first name and last name,Person.Person,"SELECT a.FirstName, a.LastName FROM Person.Person AS a WHERE EXISTS (SELECT * FROM HumanResources.Employee AS b WHERE a.BusinessEntityID = b.BusinessEntityID AND a.LastName = 'Johnson') ;" From the following tables write a query in SQL to find stores whose name is the same name as a vendor,Sales.Store,SELECT DISTINCT s.Name FROM Sales.Store AS s WHERE EXISTS (SELECT * FROM Purchasing.Vendor AS v WHERE s.Name = v.Name) ; From the following tables write a query in SQL to find employees of departments that start with P Return first name last name job title,Person.Person,"SELECT p.FirstName, p.LastName, e.JobTitle FROM Person.Person AS p JOIN HumanResources.Employee AS e ON e.BusinessEntityID = p.BusinessEntityID WHERE EXISTS (SELECT * FROM HumanResources.Department AS d JOIN HumanResources.EmployeeDepartmentHistory AS edh ON d.DepartmentID = edh.DepartmentID WHERE e.BusinessEntityID = edh.BusinessEntityID AND d.Name LIKE 'P%') ;" From the following tables write a query in SQL to find all employees that do not belong to departments whose names begin with P,Person.Person,"SELECT p.FirstName, p.LastName, e.JobTitle FROM Person.Person AS p JOIN HumanResources.Employee AS e ON e.BusinessEntityID = p.BusinessEntityID WHERE NOT EXISTS (SELECT * FROM HumanResources.Department AS d JOIN HumanResources.EmployeeDepartmentHistory AS edh ON d.DepartmentID = edh.DepartmentID WHERE e.BusinessEntityID = edh.BusinessEntityID AND d.Name LIKE 'P%') ORDER BY LastName, FirstName ;" select employees who work as design engineers tool designers or marketing assistants,Person.Person,"SELECT p.FirstName, p.LastName, e.JobTitle FROM Person.Person AS p JOIN HumanResources.Employee AS e ON p.BusinessEntityID = e.BusinessEntityID WHERE e.JobTitle IN ('Design Engineer', 'Tool Designer', 'Marketing Assistant');" From the following tables write a query in SQL to identify all SalesPerson IDs for employees with sales quotas over $250 000 Return first name last name of the sales persons,Person.Person,"SELECT p.FirstName, p.LastName FROM Person.Person AS p JOIN Sales.SalesPerson AS sp ON p.BusinessEntityID = sp.BusinessEntityID WHERE p.BusinessEntityID IN (SELECT BusinessEntityID FROM Sales.SalesPerson WHERE SalesQuota > 250000);" From the following tables write a query in SQL to find the salespersons who do not have a quota greater than $250 000 Return first name and last name,Person.Person,"SELECT p.FirstName, p.LastName FROM Person.Person AS p JOIN Sales.SalesPerson AS sp ON p.BusinessEntityID = sp.BusinessEntityID WHERE p.BusinessEntityID NOT IN (SELECT BusinessEntityID FROM Sales.SalesPerson WHERE SalesQuota > 250000);" From the following tables write a query in SQL to identify salesorderheadersalesreason and SalesReason tables with the same salesreasonid,Sales.salesorderheadersalesreason,SELECT * FROM sales.salesorderheadersalesreason WHERE salesreasonid IN (SELECT salesreasonid FROM sales.SalesReason); find all telephone numbers that have area code 415 Returns the first name last name and phonenumber Sort the result set in ascending order by lastname,Person.Person,"SELECT p.FirstName, p.LastName, ph.PhoneNumber FROM Person.PersonPhone AS ph INNER JOIN Person.Person AS p ON ph.BusinessEntityID = p.BusinessEntityID WHERE ph.PhoneNumber LIKE '415%' ORDER by p.LastName;" From the following tables write a query in SQL to identify all people with the first name 'Gail' with area codes other than 415 Return first name last name telephone number Sort the result set in ascending order on lastname,Person.Person,"SELECT p.FirstName, p.LastName, ph.PhoneNumber FROM Person.PersonPhone AS ph INNER JOIN Person.Person AS p ON ph.BusinessEntityID = p.BusinessEntityID WHERE ph.PhoneNumber NOT LIKE '415%' AND p.FirstName = 'Gail' ORDER BY p.LastName;" From the following tables write a query in SQL to find all Silver colored bicycles with a standard price under $400 Return ProductID Name Color StandardCost,Production.Product,"SELECT ProductID, Name, Color, StandardCost FROM Production.Product WHERE ProductNumber LIKE 'BK-%' AND Color = 'Silver' AND NOT StandardCost > 400;" retrieve the names of Quality Assurance personnel working the evening or night shifts Return first name last name shift,HumanResources.EmployeeDepartmentHistory,"SELECT FirstName, LastName, Shift FROM HumanResources.vEmployeeDepartmentHistory WHERE Department = 'Quality Assurance' AND (Shift = 'Evening' OR Shift = 'Night');" list all people with three-letter first names ending in 'an' Sort the result set in ascending order on first name Return first name and last name,Person.Person,"SELECT FirstName, LastName FROM Person.Person WHERE FirstName LIKE '_an' ORDER BY FirstName;" convert the order date in the 'America/Denver' time zone Return salesorderid order date and orderdate_timezoneade,Sales.SalesOrderHeader,"SELECT SalesOrderID, OrderDate, OrderDate ::timestamp AT TIME ZONE 'America/Denver' AS OrderDate_TimeZonePST FROM Sales.SalesOrderHeader;" convert order date in the 'America/Denver' time zone and also convert from 'America/Denver' time zone to 'America/Chicago' time zone,Sales.SalesOrderHeader,"SELECT SalesOrderID, OrderDate, OrderDate ::timestamp AT TIME ZONE 'America/Denver' AS OrderDate_TimeZoneAMDEN, OrderDate ::timestamp AT TIME ZONE 'America/Denver' AT TIME ZONE 'America/Chicago' AS OrderDate_TimeZoneAMCHI FROM Sales.SalesOrderHeader;" From the following table wirte a query in SQL to search for rows with the 'green_' character in the LargePhotoFileName column Return all columns,Production.ProductPhoto,SELECT * FROM Production.ProductPhoto WHERE LargePhotoFileName LIKE '%greena_%' ESCAPE 'a' ; From the following tables write a query in SQL to obtain mailing addresses for companies in cities that begin with PA outside the United States (US) Return AddressLine1 AddressLine2 City PostalCode CountryRegionCode,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%' ;" specify that a JOIN clause can join multiple values Return ProductID product Name and Color,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;" find the SalesPersonID salesyear totalsales salesquotayear salesquota and amt_above_or_below_quota columns Sort the result set in ascending order on SalesPersonID and SalesYear columns,Sales.SalesOrderHeader,"WITH Sales_CTE (SalesPersonID, TotalSales, SalesYear) AS ( SELECT SalesPersonID, SUM(TotalDue) AS TotalSales, DATE_PART('year',OrderDate) AS SalesYear FROM Sales.SalesOrderHeader WHERE SalesPersonID IS NOT NULL GROUP BY SalesPersonID, DATE_PART('year',OrderDate) ), Sales_Quota_CTE (BusinessEntityID, SalesQuota, SalesQuotaYear) AS ( SELECT BusinessEntityID, SUM(SalesQuota)AS SalesQuota, DATE_PART('year',QuotaDate) AS SalesQuotaYear FROM Sales.SalesPersonQuotaHistory GROUP BY BusinessEntityID, DATE_PART('year',QuotaDate) ) SELECT SalesPersonID , SalesYear , CAST(TotalSales as VARCHAR(10)) AS TotalSales , SalesQuotaYear , CAST(TotalSales as VARCHAR(10)) AS SalesQuota , CAST (TotalSales -SalesQuota as VARCHAR(10)) AS Amt_Above_or_Below_Quota FROM Sales_CTE JOIN Sales_Quota_CTE ON Sales_Quota_CTE.BusinessEntityID = Sales_CTE.SalesPersonID AND Sales_CTE.SalesYear = Sales_Quota_CTE.SalesQuotaYear ORDER BY SalesPersonID, SalesYear;" From the following tables write a query in SQL to return the cross product of BusinessEntityID and Department columns,"The following example returns the cross product of the two tables Employee and Department in the AdventureWorks2019 database. A list of all possible combinations of BusinessEntityID rows and all Department name rows are returned.","SELECT e.BusinessEntityID, d.Name AS Department FROM HumanResources.Employee AS e CROSS JOIN HumanResources.Department AS d ORDER BY e.BusinessEntityID, d.Name ;" From the following tables write a query in SQL to return the SalesOrderNumber ProductKey and EnglishProductName columns,Sales.SalesOrderDetail,"SELECT fis.SalesOrderid, dp.Productid, dp.Name FROM sales.salesorderdetail AS fis INNER JOIN production.product AS dp ON dp.Productid = fis.Productid;" From the following tables write a query in SQL to return all orders with IDs greater than 60000,Sales.SalesOrderDetail,"SELECT fis.SalesOrderid, dp.Productid, dp.Name FROM sales.salesorderdetail AS fis JOIN production.product AS dp ON dp.Productid = fis.Productid WHERE fis.SalesOrderid > 60000 ORDER BY fis.SalesOrderid;" From the following tables write a query in SQL to retrieve the SalesOrderid A NULL is returned if no orders exist for a particular Territoryid Return territoryid countryregioncode and salesorderid Results are sorted by SalesOrderid so that NULLs appear at the top,sales.salesterritory,"SELECT dst.Territoryid, dst.countryregioncode, fis.SalesOrderid FROM sales.salesterritory AS dst LEFT OUTER JOIN sales.salesorderheader AS fis ON dst.Territoryid = fis.Territoryid ORDER BY fis.SalesOrderid;" return all rows from both joined tables but returns NULL for values that do not match from the other table Return territoryid countryregioncode and salesorderid Results are sorted by SalesOrderid,sales.salesterritory,"SELECT dst.Territoryid, dst.countryregioncode, fis.SalesOrderid FROM sales.salesterritory AS dst FULL outer JOIN sales.salesorderheader AS fis ON dst.Territoryid = fis.Territoryid ORDER BY fis.SalesOrderid;" From the following tables write a query in SQL to return a cross-product Order the result set by SalesOrderid,sales.salesterritory,"SELECT dst.Territoryid, fis.SalesOrderid FROM sales.salesterritory AS dst CROSS JOIN sales.salesorderheader AS fis ORDER BY fis.SalesOrderid;" return all customers with BirthDate values after January 1 1970 and the last name 'Smith' Return businessentityid jobtitle and birthdate Sort the result set in ascending order on birthday,HumanResources.Employee,"SELECT businessentityid, jobtitle, birthdate FROM (SELECT * FROM humanresources.employee WHERE BirthDate > '1988-09-01') AS EmployeeDerivedTable WHERE jobtitle = 'Production Technician - WC40' ORDER BY birthdate;" return the rows with different firstname values from Adam Return businessentityid persontype firstname middlename and lastname Sort the result set in ascending order on firstname,Person.Person,"SELECT businessentityid, persontype, firstname, middlename,lastname from person.person WHERE firstname IS DISTINCT FROM 'Adam' order by firstname;" find the rows where firstname doesn't differ from Adam's firstname Return businessentityid persontype firstname middlename and lastname Sort the result set in ascending order on firstname,Person.Person,"SELECT businessentityid, persontype, firstname, middlename,lastname from person.person WHERE firstname IS not DISTINCT FROM 'Adam' order by firstname;" find the rows where middlename differs from NULL Return businessentityid persontype firstname middlename and lastname Sort the result set in ascending order on firstname,Person.Person,"SELECT businessentityid, persontype, firstname, middlename,lastname from person.person WHERE middlename IS DISTINCT FROM NULL order by firstname;" identify the rows with a middlename that is not NULL Return businessentityid persontype firstname middlename and lastname Sort the result set in ascending order on firstname,Person.Person,"SELECT businessentityid, persontype, firstname, middlename,lastname from person.person WHERE middlename IS not DISTINCT FROM NULL order by firstname;" fetch all products with a weight of less than 10 pounds or unknown color Return the name weight and color for the product Sort the result set in ascending order on name,Production.Product,"SELECT Name, Weight, Color FROM Production.Product WHERE Weight < 10.00 OR Color IS NULL ORDER BY Name;" list the salesperson whose salesytd begins with 1 Convert SalesYTD and current date in text format,Sales.SalesPerson,"SELECT BusinessEntityID, SalesYTD, cast (SalesYTD as varchar) AS MoneyDisplayStyle1, now() AS CurrentDate, cast(now() as varchar) AS DateDisplayStyle3 FROM Sales.SalesPerson WHERE CAST(SalesYTD AS VARCHAR(20) ) LIKE '1%';" return the count of employees by Name and Title Name and company total Filter the results by department ID 12 or 14 For each row identify its aggregation level in the Title column,HumanResources.Employee,"SELECT D.Name ,CASE WHEN GROUPING(D.Name, E.JobTitle) = 0 THEN E.JobTitle WHEN GROUPING(D.Name, E.JobTitle) = 1 THEN concat('Total :',d.name) WHEN GROUPING(D.Name, E.JobTitle) = 3 THEN 'Company Total:' ELSE 'Unknown' END AS ""Job Title"" ,COUNT(E.BusinessEntityID) AS ""Employee Count"" FROM HumanResources.Employee E INNER JOIN HumanResources.EmployeeDepartmentHistory DH ON E.BusinessEntityID = DH.BusinessEntityID INNER JOIN HumanResources.Department D ON D.DepartmentID = DH.DepartmentID WHERE DH.EndDate IS NULL AND D.DepartmentID IN (12,14) GROUP BY ROLLUP(D.Name, E.JobTitle);" From the following tables write a query in SQL to return only rows with a count of employees by department Filter the results by department ID 12 or 14 Return name jobtitle grouping level and employee count,HumanResources.Employee,"SELECT D.Name ,E.JobTitle ,GROUPING(D.Name, E.JobTitle) AS ""Grouping Level"" ,COUNT(E.BusinessEntityID) AS ""Employee Count"" FROM HumanResources.Employee AS E INNER JOIN HumanResources.EmployeeDepartmentHistory AS DH ON E.BusinessEntityID = DH.BusinessEntityID INNER JOIN HumanResources.Department AS D ON D.DepartmentID = DH.DepartmentID WHERE DH.EndDate IS NULL AND D.DepartmentID IN (12,14) GROUP BY ROLLUP(D.Name, E.JobTitle) HAVING GROUPING(D.Name, E.JobTitle) = 1;" From the following tables write a query in SQL to return only the rows that have a count of employees by title Filter the results by department ID 12 or 14 Return name jobtitle grouping level and employee count,HumanResources.Employee,"SELECT D.Name ,E.JobTitle ,GROUPING(D.Name, E.JobTitle) AS ""Grouping Level"" ,COUNT(E.BusinessEntityID) AS ""Employee Count"" FROM HumanResources.Employee AS E INNER JOIN HumanResources.EmployeeDepartmentHistory AS DH ON E.BusinessEntityID = DH.BusinessEntityID INNER JOIN HumanResources.Department AS D ON D.DepartmentID = DH.DepartmentID WHERE DH.EndDate IS NULL AND D.DepartmentID IN (12,14) GROUP BY ROLLUP(D.Name, E.JobTitle) HAVING GROUPING(D.Name, E.JobTitle) = 0;" return the difference in sales quotas for a specific employee over previous calendar quarters Sort the results by salesperson with businessentity id 277 and quotadate year 2012 or 2013,sales.salespersonquotahistory,"SELECT quotadate AS Year, date_part('quarter',quotadate) AS Quarter, SalesQuota AS SalesQuota, LAG(SalesQuota) OVER (ORDER BY date_part('year',quotadate), date_part('quarter',quotadate)) AS PrevQuota, SalesQuota - LAG(SalesQuota) OVER (ORDER BY date_part('year',quotadate), date_part('quarter',quotadate)) AS Diff FROM sales.salespersonquotahistory WHERE businessentityid = 277 AND date_part('year',quotadate) IN (2012, 2013) ORDER BY date_part('year',quotadate), date_part('quarter',quotadate);" return a truncated date with 4 months added to the orderdate,sales.salesorderheader,"SELECT orderdate,DATE_TRUNC('month', (select orderdate + interval '4 month')) FROM Sales.salesorderheader;" return the orders that have sales on or after December 2011 Return salesorderid MonthOrderOccurred salespersonid customerid subtotal Running Total and actual order date,sales.salesorderheader,"SELECT salesorderid, DATE_TRUNC('month', orderdate) AS MonthOrderOccurred, salespersonid, customerid, subtotal, SUM(subtotal) OVER ( PARTITION BY customerid ORDER BY orderdate, salesorderid ROWS UNBOUNDED PRECEDING ) AS RunningTotal, orderdate AS ActualOrderDate FROM Sales.salesorderheader WHERE salespersonid IS NOT NULL AND DATE_TRUNC('month', orderdate) >= '2011-12-01'" repeat the 0 character four times before productnumber Return name productnumber and newly created productnumber,Production.Product,"SELECT Name, productnumber , concat(REPEAT('0', 4) , productnumber) AS fullProductNumber FROM Production.Product ORDER BY Name;" find all special offers When the maximum quantity for a special offer is NULL return MaxQty as zero,Sales.SpecialOffer,"SELECT Description, DiscountPct, MinQty, coalesce(MaxQty, 0.00) AS ""Max Quantity"" FROM Sales.SpecialOffer;" find all products that have NULL in the weight column Return name and weight,Production.Product,"SELECT Name, Weight FROM Production.Product WHERE Weight IS NULL;" find the data from the first column that has a non-null value Return name color productnumber and firstnotnull column,Production.Product,"SELECT Name, Color, ProductNumber, COALESCE(Color, ProductNumber) AS FirstNotNull FROM production.Product ;" From the following tables write a query in SQL to return rows only when both the productid and startdate values in the two tables matches,Production.workorder,"SELECT a.productid, a.startdate FROM production.workorder AS a WHERE EXISTS (SELECT * FROM production.workorderrouting AS b WHERE (a.productid = b.productid and a.startdate=b.actualstartdate)) ;" From the following tables write a query in SQL to return rows except both the productid and startdate values in the two tables matches,Production.workorder,"SELECT a.productid, a.startdate FROM production.workorder AS a WHERE not EXISTS (SELECT * FROM production.workorderrouting AS b WHERE (a.productid = b.productid and a.startdate=b.actualstartdate)) ;" find all creditcardapprovalcodes starting with 1 and the third digit is 6 Sort the result set in ascending order on orderdate,sales.salesorderheader,"SELECT salesorderid, orderdate, creditcardapprovalcode FROM sales.salesorderheader WHERE creditcardapprovalcode LIKE '1_6%' ORDER by orderdate;" concatenate character and date data types for the order ID 50001,sales.salesorderheader,"SELECT concat('The order is due on ' , cast(DueDate as VARCHAR(12))) FROM Sales.SalesOrderHeader WHERE SalesOrderID = 50001;" form one long string to display the last name and the first initial of the vice presidents Sort the result set in ascending order on lastname,sales.salesorderheader,"SELECT concat(LastName ,',' ,' ' , SUBSTRING(FirstName, 1, 1), '.') AS Name, e.JobTitle FROM Person.Person AS p JOIN HumanResources.Employee AS e ON p.BusinessEntityID = e.BusinessEntityID WHERE e.JobTitle LIKE 'Vice%' ORDER BY LastName ASC;" return only the rows for Product that have a product line of R and that have days to manufacture that is less than 4 Sort the result set in ascending order on name,Production.Product,"SELECT Name, ProductNumber, ListPrice AS Price FROM Production.Product WHERE ProductLine = 'R' AND DaysToManufacture < 4 ORDER BY Name ASC;" From the following tables write a query in SQL to return total sales and the discounts for each product Sort the result set in descending order on productname,Production.Product,"SELECT p.Name AS ProductName, (OrderQty * UnitPrice) as NonDiscountSales, ((OrderQty * UnitPrice) * UnitPriceDiscount) as Discounts FROM Production.Product AS p INNER JOIN Sales.SalesOrderDetail AS sod ON p.ProductID = sod.ProductID ORDER BY ProductName DESC;" From the following tables write a query in SQL to calculate the revenue for each product in each sales order Sort the result set in ascending order on productname,Production.Product,"SELECT 'Total income is', ((OrderQty * UnitPrice) * (1.0 - UnitPriceDiscount)), ' for ', p.Name AS ProductName FROM Production.Product AS p INNER JOIN Sales.SalesOrderDetail AS sod ON p.ProductID = sod.ProductID ORDER BY ProductName ASC;" From the following tables write a query in SQL to retrieve one instance of each product name whose product model is a long sleeve logo jersey and the ProductModelID numbers match between the tables,Production.Product,SELECT DISTINCT Name FROM Production.Product AS p WHERE EXISTS (SELECT * FROM Production.ProductModel AS pm WHERE p.ProductModelID = pm.ProductModelID AND pm.Name LIKE 'Long-Sleeve Logo Jersey%'); From the following tables write a query in SQL to retrieve the first and last name of each employee whose bonus in the SalesPerson table is 5000,Person.Person,"SELECT DISTINCT p.LastName, p.FirstName FROM Person.Person AS p JOIN HumanResources.Employee AS e ON e.BusinessEntityID = p.BusinessEntityID WHERE 5000.00 IN (SELECT Bonus FROM Sales.SalesPerson AS sp WHERE e.BusinessEntityID = sp.BusinessEntityID);" find product models where the maximum list price is more than twice the average,Production.Product,SELECT p1.ProductModelID FROM Production.Product AS p1 GROUP BY p1.ProductModelID HAVING MAX(p1.ListPrice) <= (SELECT AVG(p2.ListPrice) * 2 FROM Production.Product AS p2 WHERE p1.ProductModelID = p2.ProductModelID); find the names of employees who have sold a particular product,Person.Person,"SELECT DISTINCT pp.LastName, pp.FirstName FROM Person.Person pp JOIN HumanResources.Employee e ON e.BusinessEntityID = pp.BusinessEntityID WHERE pp.BusinessEntityID IN (SELECT SalesPersonID FROM Sales.SalesOrderHeader WHERE SalesOrderID IN (SELECT SalesOrderID FROM Sales.SalesOrderDetail WHERE ProductID IN (SELECT ProductID FROM Production.Product p WHERE ProductNumber = 'BK-M68B-42')));" Create a table public gloves from Production ProductModel for the ProductModelID 3 and 4 include the contents of the ProductModelID and Name columns of both the tables,Production.ProductModel,"SELECT ProductModelID, Name INTO public.Gloves FROM Production.ProductModel WHERE ProductModelID IN (3, 4);"