Wednesday, March 21, 2012

Newbie Query Problem

I want to use the same field in one table and return multiple columns for
different criteria. In other words...
First column
SUM(Sales.NetSales) as 'Total Sales').
Then I want a second column as
SUM(Sales.NetSales) as 'Category 02' where Sales.categoryid='02'.
Is this reasonable? I am sure that it is a simple thing that I am just
ignorant of.
Thanks.
ChuckChuck,
Try:
--rows
SELECT CategoryID, SUM(Sales) AS 'Total Sales'
FROM NetSales
GROUP BY CategoryID
--or
--columns
SELECT 'Category 1' = (SELECT SUM(Sales) AS 'Total Sales'FROM NetSales WHERE
CategoryID = 1),
'Category 2' = (SELECT SUM(Sales) AS 'Total Sales'FROM NetSales WHERE
CategoryID = 2)
HTH
Jerry
"Chuck" <Chuck@.discussions.microsoft.com> wrote in message
news:94FD5CDE-C7BE-43CF-857C-2A847675A1EF@.microsoft.com...
>I want to use the same field in one table and return multiple columns for
> different criteria. In other words...
> First column
> SUM(Sales.NetSales) as 'Total Sales').
> Then I want a second column as
> SUM(Sales.NetSales) as 'Category 02' where Sales.categoryid='02'.
> Is this reasonable? I am sure that it is a simple thing that I am just
> ignorant of.
> Thanks.
> Chuck|||SELECT
(SELECT SUM(NetSales) FROM Sales) as TotalSales,
(SELECT SUM(NetSales) FROM Sales WHERE categoryid = '02') as Category02
Chuck wrote:
> I want to use the same field in one table and return multiple columns for
> different criteria. In other words...
> First column
> SUM(Sales.NetSales) as 'Total Sales').
> Then I want a second column as
> SUM(Sales.NetSales) as 'Category 02' where Sales.categoryid='02'.
> Is this reasonable? I am sure that it is a simple thing that I am just
> ignorant of.
> Thanks.
> Chuck|||On Mon, 19 Sep 2005 11:58:06 -0700, Chuck wrote:

>I want to use the same field in one table and return multiple columns for
>different criteria. In other words...
>First column
>SUM(Sales.NetSales) as 'Total Sales').
>Then I want a second column as
>SUM(Sales.NetSales) as 'Category 02' where Sales.categoryid='02'.
>Is this reasonable? I am sure that it is a simple thing that I am just
>ignorant of.
>Thanks.
>Chuck
Hi Chuck,
Here's a way that requires only one pass over the table:
SELECT SUM(NetSales) AS 'Total Sales',
SUM(CASE WHEN categoryid = '02' THEN NetSales ELSE NULL END) AS
'Category 02'
FROM YourTable
Best, Hugo
--
(Remove _NO_ and _SPAM_ to get my e-mail address)

No comments:

Post a Comment