Question

I am trying to group some columns in certain way based on some criteria. My criteria in this situation is: if Category_Name is "Performance" i want "Sales" and "Cost" to go in the Grouping column and their values to go in the Amount column. If Category_Name is "Quality" i want the "Rev" to go into Grouping column and its value to go into the Amount column. Please note that i am using Netezza as my database. Here is what i have now: CURRENT TABLE OR CURRENT ISSUE:

enter image description here

DESIRED RESULTS:

enter image description here

P.S. I AM USING NETEZZA

Was it helpful?

Solution

The example and solution below were done with ANSI SQL in SQL Server 2012. This should work fine in NETEZZA if it is ANSI compliant.

First, create a sample table in TEMPDB and load with data. This is SQL Server specific. Can be any testing database you create.

-- Use temp db
USE TEMPDB;
GO

-- Create a temp table
CREATE TABLE T1
(
  LOCATION_CODE CHAR(2),
  PART_NUM CHAR(2),
  CATEGORY_NAME VARCHAR(25),
  YEAR_NUM INT,
  SALES_NUM INT,
  COST_NUM INT,
  REV_NUM INT
);

-- Add 3 row of data
INSERT INTO T1 
VALUES ('NY', '1A', 'Performance', 2001, 100, 35, 45);

INSERT INTO T1 
VALUES ('IL', '2E', 'Quality', 2002, 250, 150, 44);

INSERT INTO T1 
VALUES ('IL', '4F', 'Performance', 2003, 355, 280, 33);
GO

-- Show the data
SELECT * FROM T1;
GO

Basically, what you want to do is re-organize the data. Make two different rows for Performance data and one row for Quality data. Then order all the rows by location and part number.

The UNION ALL is what you want. This statement does not remove duplicates between result sets. Three queries one for each case, a UNION ALL between them, and a ORDER BY at the end will produce the results you are looking for.

http://technet.microsoft.com/en-us/library/ms180026.aspx

Here is the sample code.

-- Break Performance into 2 rows - A
SELECT 
  LOCATION_CODE,
  PART_NUM,
  CATEGORY_NAME,
  'Sales' as GROUPED,
  SALES_NUM as AMOUNT
FROM T1
WHERE CATEGORY_NAME = 'Performance'
UNION ALL
-- Break Performance into 2 rows - B
SELECT 
  LOCATION_CODE,
  PART_NUM,
  CATEGORY_NAME,
  'Cost' as GROUPED,
  COST_NUM as AMOUNT
FROM T1
WHERE CATEGORY_NAME = 'Performance'
UNION ALL
-- One row for Quality
SELECT 
  LOCATION_CODE,
  PART_NUM,
  CATEGORY_NAME,
  'Rev' as GROUPED,
  REV_NUM as AMOUNT
FROM T1
WHERE CATEGORY_NAME = 'Quality'

-- Order the results
ORDER BY LOCATION_CODE, PART_NUM;

Here is a screen shot of the result window in SSMS.

enter image description here

This should solve your problem.

Sincerely, John - The Crafty DBA

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top