How to make 2 pivots for same fields
- User
How to make 2 pivots for same fields
- Assistant
To make 2 pivots for the same fields, you can follow these steps using SQL:
-
Start by creating a table with the desired fields. For example, let's say we have a table named 'sales_data' with fields 'product', 'region', and 'sales_amount'.
-
Write the SQL query to pivot the data based on one field, for example, 'region'. This query will aggregate the sales_amount for each region.
sqlSELECT product, SUM(CASE WHEN region = 'North' THEN sales_amount ELSE 0 END) AS north_sales, SUM(CASE WHEN region = 'South' THEN sales_amount ELSE 0 END) AS south_sales, SUM(CASE WHEN region = 'East' THEN sales_amount ELSE 0 END) AS east_sales, SUM(CASE WHEN region = 'West' THEN sales_amount ELSE 0 END) AS west_sales FROM sales_data GROUP BY product; -
- User
How to make two pivots for same fields mssql
- Assistant
In Microsoft SQL Server (MS SQL), you can achieve two pivots for the same fields by using the PIVOT function in two separate select statements. Here's an example of how you can do this:
Assuming you have a table named 'sales_data' with fields 'product', 'region', and 'sales_amount', you can create two separate pivots for the 'product' and 'region' fields as follows:
- Pivot the data based on the 'product' field:
sqlSELECT region, [Product A], [Product B], [Product C] FROM (SELECT region, product, sales_amount FROM sales_data) AS SourceTable PIVOT ( SUM(sales_amount) FOR product IN ([Product A], [Product B], [Product C]) ) AS PivotTable;- Pivot the data based on the 'region' field:
sql