Skip to content
Advertisement

Using columns from different tables to create one table

I am not sure how I can get this code to have three columns for each category (Portrait,Landscape, and Abstract). As of now, it only has one column and all three of these values computed values:

SELECT SUM(Price) AS TotalSales_Portrait
FROM Photo
WHERE TransID IS NOT NULL AND PhotoID IN (
SELECT PhotoID
FROM Models) 

UNION

SELECT SUM(Price) AS TotalSales_Landscape
FROM Photo
WHERE TransID IS NOT NULL AND PhotoID IN (
SELECT PhotoID
FROM Landscape)

UNION

SELECT SUM(Price) AS TotalSales_Abstract
FROM Photo
WHERE TransID IS NOT NULL AND PhotoID IN (
SELECT PhotoID
FROM Abstract)

Query output

Any advice is greatly appreciated

Advertisement

Answer

This can be done by using pivot as follows

select *
from (
SELECT MAX('Portrait') as photo_type,SUM(Price) AS Total_Sales
  FROM Photo
WHERE TransID IS NOT NULL AND PhotoID IN (
SELECT PhotoID
  FROM Models) 
UNION
SELECT MAX('Landscape'),SUM(Price) AS Total_Sales
FROM Photo
WHERE TransID IS NOT NULL AND PhotoID IN (
SELECT PhotoID
FROM Landscape)
)x
pivot (sum(total_sales) for photo_type in(Portrait,Landscape))y
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement