Input
stringlengths
34
376
Table
stringlengths
11
229
Output
stringlengths
57
1.01k
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);