Question on sql script

Could someone please help, I have started a new position in reporting, and 
I'm major learning on the job.  I need to create a script to extract data 
from a single table.  The fields are Customer, Units, Sales.  The problem I'm 
having is the following.  I know that I need to do some type of pivot query 
to extract the data in the way requested.  See Below

(Requested Results)

Customer  Units08-09 Sales08-09  Units09-10 Sales09-10   DiffUnits Diff Sales


I have created a sample script with a temp table and data and what I have 
come up with so far, but I just can't figure out how to group that data to 
get the needed results. 

http://sql-servers.com/nopaste/index.php?show=706

Could someone Please help!  Once I see it done I can understand how to do 
this type of thing in the future 


Thanks in advance

Dave.




-- 
Dave
0
Utf
9/11/2010 4:08:06 PM
sqlserver.programming 1873 articles. 0 followers. Follow

2 Replies
958 Views

Similar Articles

[PageSpeed] 10

I'm not exactly sure what you wanted and the sample result you showed 
doesn't seem to go with the sample data you provided (BTW, thanks for 
providing the DDL and sample data).  But I think you want

With cte As
(Select Customer,
  Sum(Case When Year(orderdate) = 2009 Then Units Else 0 End) As Units0809,
  Sum(Case When Year(orderdate) = 2009 Then Sales Else 0 End) As Sales0809,
  Sum(Case When Year(orderdate) = 2010 Then Units Else 0 End) As Units0910,
  Sum(Case When Year(orderdate) = 2010 Then Sales Else 0 End) As Sales0910
From #temp123
Where orderdate >= '20090101' And orderdate < '20110101'
Group By Customer)
Select Customer, Units0809, Sales0809, Units0910, Sales0910,
  Units0910-Units0809 As DiffUnits, Sales0910 - Sales0809 As DiffSales
From cte;

Tom

"David" <duckkiller53@gmail.com> wrote in message 
news:7663F78A-6DD6-4105-9161-F3E58365E110@microsoft.com...
> Could someone please help, I have started a new position in reporting, and
> I'm major learning on the job.  I need to create a script to extract data
> from a single table.  The fields are Customer, Units, Sales.  The problem 
> I'm
> having is the following.  I know that I need to do some type of pivot 
> query
> to extract the data in the way requested.  See Below
>
> (Requested Results)
>
> Customer  Units08-09 Sales08-09  Units09-10 Sales09-10   DiffUnits Diff 
> Sales
>
>
> I have created a sample script with a temp table and data and what I have
> come up with so far, but I just can't figure out how to group that data to
> get the needed results.
>
> http://sql-servers.com/nopaste/index.php?show=706
>
> Could someone Please help!  Once I see it done I can understand how to do
> this type of thing in the future
>
>
> Thanks in advance
>
> Dave.
>
>
>
>
> -- 
> Dave 

0
Tom
9/11/2010 4:53:19 PM
I have spent some time on the problem which I asked about in my original 
post.  I have come up with a script that I think is close to what I need, but 
it does not use the PIVOT query technology.  Here is what I came up with.

IS THERE A BETTER WAY TO DO THIS WITH  PIVOT QUERY?

CREATE TABLE #temp123
(
Customer varchar(20),
Units integer,
Sales integer,
orderdate datetime
)

CREATE TABLE #temp2
(
 Customer varchar(20),
 Units0809 integer,
 Sales0909 integer,
 Units0910 integer,
 Sales0910 integer
)



INSERT #temp2
	Select Customer, 
           Units0809 = SUM(case when orderdate >= '01/01/2008' and 
                               orderdate <= '12/31/2009' THEN Units end),
           Sales0809 = SUM(case when orderdate >= '01/01/2008' and
                               orderdate <= '12/31/2009' THEN Sales end),    
        
           Units0910 = SUM(case when orderdate >= '01/01/2009' and 
                               orderdate <= '12/31/2010' THEN Units end),
           Sales0910 = SUM(case when orderdate >= '01/01/2009' and 
                               orderdate <= '12/31/2010' THEN Sales end)
            FROM #temp123 GROUP BY Customer


select * from #temp123
select * from #temp2
-- 
Dave


"David" wrote:

> Could someone please help, I have started a new position in reporting, and 
> I'm major learning on the job.  I need to create a script to extract data 
> from a single table.  The fields are Customer, Units, Sales.  The problem I'm 
> having is the following.  I know that I need to do some type of pivot query 
> to extract the data in the way requested.  See Below
> 
> (Requested Results)
> 
> Customer  Units08-09 Sales08-09  Units09-10 Sales09-10   DiffUnits Diff Sales
> 
> 
> I have created a sample script with a temp table and data and what I have 
> come up with so far, but I just can't figure out how to group that data to 
> get the needed results. 
> 
> http://sql-servers.com/nopaste/index.php?show=706
> 
> Could someone Please help!  Once I see it done I can understand how to do 
> this type of thing in the future 
> 
> 
> Thanks in advance
> 
> Dave.
> 
> 
> 
> 
> -- 
> Dave
0
Utf
9/12/2010 10:15:03 PM
Reply:

Similar Artilces:

sql 2005 views
I am beginning the process of converting a 15 yr old Access db (frontend) into a website application. It might be 15yo but is still very much used today and has gone thru all the updates over time. The back end is sql server 2005. Much in the front end uses sql views. How are views treated in asp.net sqldatasource? As stored proc, view, table, or ??? How are they referred to in a sqldatasource? Same as a stored proc? Any samples/examples/links of using a view? Thanks...John "JohnE" <JohnE@discussions.microsoft.com> wrote in message news:B3BC420E-1EFD...

Backup question
I've moved to a new pc and for some reason I thought that when you backed up, a new file was created. Am I right? At the moment, it's just backing up to the backup file. So I've just just my working file and my backup file. Please could you clarify this? Thanks again. In microsoft.public.money, abc wrote: >I've moved to a new pc and for some reason I thought that when you >backed up, a new file was created. Am I right? At the moment, it's >just backing up to the backup file. So I've just just my working file >and my backup file. P...

how SIN, COS and TAN works on sql server
I ran this: declare @f float set @f = 30 select sin(@f) and got -0.988031624092862 What is this? "Roy Goldhammer" <royg@yahoo.com> wrote in message news:eRKvnY0#KHA.5476@TK2MSFTNGP06.phx.gbl... > I ran this: > > declare @f float > > set @f = 30 > > select sin(@f) > > and got -0.988031624092862 > > What is this? > > The values for SIN, COS, and TAN are in radians, not degrees. You are seeing the value of SIN(30 radians), which is correct. -- Dan "Dan" <news@worldofspack.com...

Question about Xml Schemas "qualified" and "unqualified"
In the textbook, there is a sentence that "Default XML namespaces(xmlns="...") helps a lot, but can also create problems, as a side effect of the rules for automatic qualification. How to understand "automatic qualification" here? Could you please give me an example? Secondly, unless otherwise specified, a schema prescribes that loal elements and attributes must be "unqualified". What does "unqualified" mean? Could you please giv eme an example? Finnaly, could you please tell me what's purpose of using these two things? Thanks a lot! ...

a question and a question
What is the correct name of the type of selection box used in "customizing Word", for example.... you select a word or operation from a list on the left pane and move it over to the right pane. Is there a template to build one of these? thanx You will have to explain more in detail what you are trying to do. -- Stefan Blom Microsoft Word MVP "cliffordjf" <cliffordjf@discussions.microsoft.com> wrote in message news:9856CCA7-8A8E-440C-A0D4-76EE4FA644E2@microsoft.com... > What is the correct name of the type of selection box used in "c...

Question about Paste Special
Hi, I have a problem sometimes with the paste special options when goin from one excel workbook to another. For example, sometimes when I cop data from one workbook and then paste special into another, I get th options that include: All, formulas, values, formats, has the option t transpose the data and paste link among other options. And the sometimes I try and paste data to another workbook and I end up th paste special options: Bitmap Image Object, picture, bitmap, and I als lose the ability to paste link. Well you can do it, but it puts it i as an object. What I want is the first past...

IE8 privacy question
I am running XP-Pro SP3 and considering upgrading from IE7 to IE8. I have read all the feature and benefit articles from MS, but have one question that remains unanswered. In IE8 there is mention of being able to restore previously viewed websites or something to that effect. I think this is on a drop down menu somewhere. 1) Does In-private viewing prevent this? 2) Does manually deleting your complete browsing history clear this? 3) Is there a registry entry that can prevent this action? 4) Is there a group policy change that can prevent this action? In essence for privacy pur...

IF AND question
Hi there, I need a function that can provide one of three answers: 1 2 1 1... 3 3 4 4... ? ? ? ?... If A1 = 1 and A2=3, answer 106; but if A1=1 and A2 = 4, answer 104; but if A1=2, regardless of A2, answer 95. The next function for column B is the same, except the answer is dependent on the value delivered from the column A function. E.g. A3 + 6 or A3 +4 or A3-5 etc. Any help would be most appreciated. -- ***** Many thanks Gamq Use the below formula for your first query. =IF(A1="","",IF(A1=2,95,IF(AND(A1=1,A2=3),106,IF(AND(A1=1,A2=4),104)))) ...

SQL 2005 Upgrade #2
I know there are Dynamics users that have completed the transition from SQL 2000 to SQL 2005. We are on Dynamics 8.0 SP5 running on SQL 2000 SP4. Step 1 of our move to 10.0 is to upgrade to SQL 2005. We're very clear about the Server side of the upgrade. I have looked for information on CustomerSource about impacts and required activities for Dynamics, but have not found much (This forum is where I have found the most). Is there any information/knowledge available? -- Tim Foster Tim, see below link for upgrade information from Dynamics 8.0 SP5 to 10.0. https://mbs.microsoft....

Microsoft Query question
I am trying to use Microsoft Query to get data from my SQL 2000 databases. The problem is that I have a few columns with names that conflict with keywords (like Identity). (Yes. I kow that keywords should be avoided but it is done and cannot be changed.) This is causing a keyword syntax error within the Query application. Oddly enough, even if I do not select the column the error still appears. And when you look at all the columns available, the keyword named column shows up in boldface. When I am doing queries in other programs I put square ("[ ]") brackets around column and table...

Question
Why did the chicken cross the road? -- Dr. Stephen Hopkins, MD "Dr. Stephen Hopkins, MD" <DrStephenHopkinsMD@discussions.microsoft.com> wrote in message news:B8434E21-DDA3-44D7-B39B-CD5A8C33A7BD@microsoft.com... > Why did the chicken cross the road? > -- > Dr. Stephen Hopkins, MD To collect her email, why else? Dr? You should be ashamed to put such a title on an idiotic off topic post !! -- Regards Steve. MS-MVP. MAIL. [DTS] UK. http://www.getsafeonline.org/ mac;1266180 Wrote: > "Dr. Stephen Hopkins, MD" <DrSte...

OWA Question #16
Hello All: Quick Question regarding OWA. We are about to finalize migration from 5.5 to 2003. We have an existing web presence already in DNS a www.mydomain.com. and running on existing web servers. With 5.5 natrually, to access OWA, it was www.mydomain.com/exchange. This will not be possible now since OWA runs off of the Exchange server instead of relying on our web server under 5.5. What's the easiest way to overcome this. Thanks If you can afford the extra license, you'll probably want to run a front-end server so no one is connecting directly to the Exchange database s...

Text Box Question
Greetings, I have been using Visio for years, however, something has happened and I can't figure out how to undo it. Basically up until today when I added a text box and entered text, the text went horizontal as it was typed. Today when I add a text box and enter text, the text goes vertical. How do I get back to the old behavior? TIA using text container shape adjusting tool (text block tool), make the text container shape wider horizontally. Have you used Asian text font recently?...check help for "vertical text" "Ray Batig" wrote: > Greetings, > &g...

401K questions
I just started a 401K at work and I'm wondering how to deal with it in Money. I've got my paycheck split into different categories currently and now I have to put the 401K amount into a category as well. I didn't see one specifically for this. What do other people use? Should I start using the 401K Manager? I haven't gone through it yet I'm just wondering if it works well and how much benefit I'll get from it. Thanks in advance! Mike You will want to create an investment account for the 401(k) and TRANSFER your contributions from your checking account to the...

VBA//Oracle Interfacing Question
All, I have been able to correct to my database but I have one question question: Within objSession I want to list all available tables and all available views. How exactly is this done? thank you. Set objSession = CreateObject("OracleInProcServer.XOraSession") Set objDatabase = objSession.OpenDatabase("", "User/Pass", 0) On Nov 16, 12:05=A0pm, jason <jason.mell...@gmail.com> wrote: > All, > > I have been able to correct to my database but I have one question > question: > > Within objSession I want to list all avail...

If / Then Question
How would I do this: IF A1="N" then I need A2 and A3 to="N/A -- pkniven ----------------------------------------------------------------------- pknivens's Profile: http://www.excelforum.com/member.php?action=getinfo&userid=2767 View this thread: http://www.excelforum.com/showthread.php?threadid=47531 pknivens Wrote: > How would I do this: > > IF A1="N" then I need A2 and A3 to="N/A" Hi pknivens In A2 and A3 use this formula > =IF(A1="N","N/A",""), this will return blank if A1 is not N, if you want it...

ROWCOUNT question
Hi All, The below is a UDF that returns the ROWCOUNT for a table. I need to know that value for WHILE loop. How do I take the Returned value from the UDF and load it intio a variable in the SP where it was called from? Or maybe there is another way. ALTER FUNCTION [dbo].[RecCount] ( @TableName CHAR(15) ) RETURNS TABLE AS RETURN ( SELECT Rows FROM sysindexes WHERE id = OBJECT_ID(@TableName) AND indid < 2 ) Thanks, Eric Eric S (xxx_noSpam@Hotmail.com) writes: > The below is a UDF that returns the ROWCOUNT for a table. I need to know > that va...

Exmerge Question #7
When I run Exmerge on a mailbox on my 2003 server to export to a PST, it will delete all emails after the copy. I thought EXmerge would "copy" not delete. is this the default? If so how can I just have it do a copy out to the PST and leave the mailbox alone. thanks Rick in "options", make sure "archive data to target store" is not selected on the "Import procedure" tab... -- Susan Conkey [MVP] "Rick" <drummer10980@gmail.com> wrote in message news:1165509540.777142.38260@16g2000cwy.googlegroups.com... > When I run Exmerge on ...

MS SQL Express 2008
Hi all, in order to increase performance of my Access 2007 application i choose to split the backend to a SQl Express 2008 Database engine. However..this seems not to function..i receive an error message saying - The Upsizing Wizard does not work with the version of Microsoft SQL server to which your project is connected..I cannot find anything related to this issue on the Microsoft Update Website.. Any suggestions? Thanks! I'm not sure, but I doubt Access 2007 can control SQL 2008. Access has never worked with SQL versions that came out later than the Access versio...

question about "delete"
I have a pointer: MyWindowClass *p = NULL; p = new MyClass(...); .... delete p; After delete p, does p equal NULL(it is in C++ standard?)? How to decide if p has been deleted? The reason I asked this question is that in my project, there are many code/files use the pointer which I need to determine is it is deleted? Can I use: if(p != NULL) delete p; I guess somewhere p has been deleted, but p still not NULL(possible?), the above code might cause problem. Hi Kathy, I typically just set p to NULL when I delete it: delete p; p = NULL; Then you can check it in other places and ...

More combining companies questions
We too have acquired another company and need to look at all of our options concerning what to do with email. We run Exchange 2003, they run Exchange 2000. What is the best way to combine the two so we can share GAL, free-busy info, etc.? No decisions have been made as far as what we are going to do with their AD. We could of course change their MX record to point to our server, update our RUS, etc., but what if we want to keep an Exchange server at their site? What has to be done to join their server to our Exchange org? If you want sync both GAL,pls check this http://www.microso...

switchboard question 12-26-07
Is there a way to put the names of different switchboard pages on the switchboard form? If you put one name on a switchboard page (in form design view), the same name appears on all the switchboard pages. I understand why this happens, but what if I want the user to be able to know which switchboard s/he is on? Thanks. PS the same thing happens if I go into form design view and put in control tip text. It puts the same text for the same-numbered menu item on two different switchboard pages. "Debbie S." wrote: > Is there a way to put the names of different switchboard ...

Some Questions about Outlook
1. what's the max size of attachment for sending email? 2. newMail notifitor: when there is a new mail, can the tary be changed to other until i check the mail? can it work with hotmail? 3. is there any function likes "To Do List"; calendar require time setting? 4. configure file backup; can i back up all of my setting? -- Me, Who I am On Sun, 7 May 2006 22:17:01 -0700, Dotku <lwjct@hotmail.com> wrote: >1. what's the max size of attachment for sending email? That would depend on your mail server/ISP. >2. newMail notifitor: when there is a new mail, can the ...

Error Installing SQL jobs during installation of CRM 4.0 trail ver
While trying to install SQL jobs during installation of CRM 4.0 trail version i get an error message. Action Microsoft.Crm.Setup.Server.InstallConfigDatabaseAction failed. Invalid user name.Failed to validate username for given domain.only existing domain usernames and email addresses are allowed Invalid user name.Failed to validate username for given domain.only existing domain usernames and email addresses are allowed can anyone help me solve out this issue ? ...

Version control for SQL Server databases
It is my understanding that version control for sql server databases can be problematic. I have been thinking about this problem on and off for a while, and over the last couple of hours the beginnings of a system have crystallized. I am going to sketch the first draft of this evolving idea below. If anyone recognizes the mechanisms as already existing in some product or solution, please let me know. If anyone recognizes problems or limitations of the system, please let me know about those too. Once again, this is just a first draft that I have been brainstorming for about 2 hours, ...