Advance PIVOT Function In SQL2005

Apr 13, 2007

Below is an example of a pivot table from the help in SQL2005.
My question: Do you have to manually define the columns ([164], [198], etc.) for the pivot?

I would like to use this for a daily report where the columns would be the dates?

Thanks.

GO
SELECT VendorID, [164] AS Emp1, [198] AS Emp2, [223] AS Emp3, [231] AS Emp4, [233] AS Emp5
FROM
(SELECT PurchaseOrderID, EmployeeID, VendorID
FROM Purchasing.PurchaseOrderHeader) p
PIVOT
(
COUNT (PurchaseOrderID)
FOR EmployeeID IN
( [164], [198], [223], [231], [233] )
) AS pvt
ORDER BY VendorID

View 3 Replies


ADVERTISEMENT

Many Thanks In Advance! - Simple Date Function - Please Help!!!

Aug 2, 2004

Hi All,

Does anyone know how to return a date the sql query analyser like (Aug 2, 2004)

Right now, the following statement returns (Aug 2, 2004 8:40PM). This is now good because I need to do a specific date search that doesn't include the time.

Many thanks in advance!!
Brad

----------------------------------------------
declare @today DateTime
Select @today = GetDate()
print @today

View 2 Replies View Related

Power Pivot :: ALL DAX Function Not Overriding Filter On Pivot Table

Oct 14, 2015

I have a simple pivot table (screenshot below) that has two variables on it: one for entry year and another for 6 month time intervals. I have very simple DAX functions that count rows to determine the population N (denominator), the number of records in the time intervals (numerator) and the simple percent of those two numbers.

The problem that I am having is that the function for the population N is not overriding the time interval on the pivot table when I use an ALL function to do so. I use ALL in other very simple pivot tables to do the same thing and it works fine.

The formula for all three are below, but the one that is the issue is the population N formula. Why ALL would not work, any other way to override the time period variable on the pivot table.

Population N (denominator):
=CALCULATE(COUNTROWS(analyticJudConsist),ALL(analyticJudConsist[CurrentTimeInCare1]))
Records in time interval (numerator):
=COUNTROWS(analyticJudConsist)
Percent:
=[countrows]/[denominatorCare]

View 13 Replies View Related

Alternative Way To PIVOT Function?

Jan 14, 2014

We are running SQL2000, and I was trying to use the PIVOT function, as you are all aware 2000 does not support the PIVOT function.

is there an alternative to the PIVOT function

here my code I was trying to use

Code:
SELECT CostSavingsNo, CostSavingType

From (Select CostSavingsNo, CostSavingType, SavingsValue FROM CostSavingsDetails) CSD

PIVOT

(SUM(SavingsValue) FOR CostSavingType IN ([1], [2], [3], [4], [5], [6], [7], [8],[9], [10], [11], [12]], [13], [14])) AS PVT

View 7 Replies View Related

Pivot Function Question

Oct 12, 2007


Below is my query and returned rows. I am pulling unique dx codes for each account. In the case below I have 14 returned rows, each having a unique dx_key (second column), which I need to display across the report horizonaly versus vertical. (see below example)

DXCode1 DXCode2 DXCode3 DXCode4 DXCode5..etc..
20190 5789 5990 2768 2449

I came across the post below by Manivannan.D.Sekaran on using the PIVOT function but I can't quite get the hang of it. Can someone give me some help please?

http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1776397&SiteID=1



--Query


select

dxo.episode_key,

dxo.dx_key,

dxo.dx_code,

dxo.dx_desc

from srm.cdmab_dx_other dxo inner join

srm.episodes e on e.episode_key=dxo.episode_key

where dxo.episode_key is not null

and e.account_number IN ('11111111230')

order by episode_key, dx_key


--Rows returned from above query

12451538 117782 20190 Hodgkin's disease, unspecified site, extranodal and solid organ sites
12451538 117783 5789 Gastrointestinal hemorrhage, unspecified
12451538 117784 5990 Urinary tract infection, site not specified
12451538 117785 2768 Hypopotassemia
12451538 117786 2449 Unspecified acquired hypothyroidism
12451538 117787 28529 Anemia of other chronic disease
12451538 117788 3051 Tobacco use disorder
12451538 117789 53540 Gastritis without mention of hemorrhage
12451538 117790 53190 Gastric ulcer without hemorrhage or perforation, without mention of obstruction
12451538 117791 5589 Noninfectious gastroenteritis and colitis
12451538 117792 56210 Diverticulosis of colon without mention of hemorrhage
12451538 117793 2113 Benign neoplasm of colon
12451538 117794 V1259 Personal history of diseases of circulatory system
12451538 117795 V011 Contact with or exposure to tuberculosis

View 8 Replies View Related

Augent Pls Help::::Is_Member() Function Returns 0 Instead Of 1 In Sql2005

Aug 10, 2007

Hello All,

I have a situation where after creating roles and addding users to the roles then when i call Is_Member('MyRole') on my development box it tells me the user is a member of the Role,
But when i detach the database and deploy on a production server and call Is_Member('MyRole') it tells me that the user is not a member of the Role....

I went on to call the system stored procedures, sp_helprolemember to actualy determine if the user is in the 'MyRole' role and the procedure returned a list which i confirmed that the user actually exists in that role..

So am pretty confused when i call Is_Member('MyRole') and it gives me 0 meaning the user is not in the role....

Plss i need help on this thanks a million


KNOW THY SELF

View 8 Replies View Related

Passing MS SQL2005 Query Result Into Javascript Function

Mar 20, 2007

I'm selecting the last latitude & longitude input from my database to put into the Google maps javascript function.
This is how I retrieve the longitude:
 <asp:SqlDataSource ID="lon" runat="server" ConnectionString="<%$ ConnectionStrings:LocateThis %>"
SelectCommand= "SELECT @lon= SELECT [lon] lon FROM [location] WHERE time = (SELECT MAX(time) FROM [location] where year < 2008)">
</asp:SqlDataSource>
I wish to input the latitude & longitude into the JAVASCRIPT function (contained in the HTML head before the ASP) something like this:
var map = new GMap2(document.getElementById("map"));var lat = <%=lat%>;var lon = <%=lon%>;var center = new GLatLng(lat,lon);map.setCenter(center, 13); 
 However, lat & long do not contain the retrieved result but rather a useless System.something string.
How do I assign the retrieved results to these variables and port them over to Javascript as required?
Many thanks!

View 14 Replies View Related

SQL Statement Performs Pivot Table Function?

Apr 13, 2006

I have the following data:Product Type Hours Controllers Development 105.0Controllers Research 1.0Controllers Sustaining 24.0How do I use SQL statement to change it to the following?Product Development Research SustainingControllers 105.0 1.0 24.0Thanks.DanYeung

View 2 Replies View Related

Transact SQL :: Duplicate PIVOT Function In 2000

Jul 1, 2015

I have a query that uses the PIVOT function and works fine in SQL 2012.  I've been asked to move the query to a database that has the compatibility level set to 80(SQL 2000).  I receive an "Incorrect syntax near" error when I try to excute the query on the SQL 2000 database.  I would like to duplicate the exiting PIVOT functionality in SQL 2000.The existing query retrieves employee names and the order that the employee should be displayed from a table.  The names will appear on the report according to the order that is retrieved from the database.  Also, the users have requested that only 5 names appear on each row of the report.  This is why the PIVOT function was needed.  Below is an example of how the existing query works.

Table
CREATE TABLE [dbo].[EmpGuest](
 [Guest_ID] [int] NOT NULL,
 [Guest_Name] [varchar](80) NULL,
 [Display_Order] [int] NULL
) ON [PRIMARY]

[code]....

View 4 Replies View Related

Power Pivot :: How Does EVALUATE Function Work

Oct 24, 2015

playing with the Power pivot , DAX. While analyzing the DAX ,I came across a function EVALUATE , but when I tried this function in excel Power Pivot workbook - =EVALUATE 'Date' where 'Date' is my one of the Power pivot table , I was writing this function within the Calculation area of the Power Pivot model.  I get the below error when I hit enter after writing the function ."The expression is not valid or appears to be incomplete..An MDX expression was expected while a full statement was specified."But in many forums I find the syntax is correct.

View 4 Replies View Related

Power Pivot :: Dates MTD Function And No Row Data

Oct 20, 2015

I have a DATESMTD function which is not working.  This is what is happening, if there is no row data for the month it creates a month to date total similar to the year to date total instead of zero.  See below my formula:

MTDSUM:=CALCULATE(SUM('Combined Years Dataset'[Net]),DATESMTD('Combined Years Dataset'[Period2]),'Date'[date])

Period 2 is a column with dates (end of monthdates) in a table called Combined Years Dataset.

So, if I have $200.00 data for Aug and no data for Sept, the system puts in 200.00 as the month to date  for Sept instead of zero.  What can I do to make the system insert zero in the month to date column instead of the $200.00.  What am I doing wrong in the formula.

View 8 Replies View Related

Power Pivot :: Using CUBEMEMBER Excel Function To Get A Member Value

May 28, 2015

In an Excel workbook I'm building a report using a PowerPivot data model.

I've a Calendar filter. If I select an year from this filter I need to show in a cell the total number of working days, present in the Calendar table as a column.

View 9 Replies View Related

Power Pivot :: Switch Statement And Function Calls

Nov 24, 2015

I created a Switch statement below that surprisingly doesn't throw any errors and some of it actually works. The problem is that the function calls in the 3rd and 4th sections of it below (in bold) are not working.

=switch(HASONEVALUE('s1JudgeIds'[JudgeName]),
values('s1JudgeIds'[JudgeName])<>"1 - All Judges" && values('s1Perm1'[Exit])<>"Still in Out-of-Home Care",CALCULATE(count(s1Perm1[entity_id]),FILTER(ALL(Time[ExitMonthCategory]),Time[ExitMonthCategory] <= MAX(Time[ExitMonthCategory]))),
values('s1JudgeIds'[JudgeName])="1 - All Judges" && values('s1Perm1'[Exit])<>"Still in Out-of-Home Care",calculate([Numerator],all('s1JudgeIds'[JudgeName])),
values('s1JudgeIds'[JudgeName])="1 - All Judges" && values('s1Perm1'[Exit])="Still in Out-of-Home Care",calculate([Numerator-stillincare],all('s1JudgeIds'[JudgeName])),
values('s1JudgeIds'[JudgeName])<>"1 - All Judges" && values('s1Perm1'[Exit])="Still in Out-of-Home Care",calculate([Numerator-stillincare])

View 24 Replies View Related

SQL Server 2008 :: Pivot Function - Additional Final Column

Mar 11, 2015

I've managed to use the pivot function using the code below which gives me the following output:

Location_Code Gt 0-1 Gt 1-2 Gt 2-3 Gt 3-4
North 10 0 3 5
West 6 3 2 0
South 4 2 8 2

This is exactly what I want but I would like an additional final column that will total the columns by location_code and weekband.

[Location_Code] AS 'Location Code'
,[Gt 0-1], [Gt 1-2], [Gt 2-3], [Gt 3-4]
from (select [WeekBand]
,[Location_Code]
, count(*) as CountOf

[Code] ....

View 7 Replies View Related

Power Pivot :: RELATED Function Shows Empty Column?

Aug 16, 2015

experimenting with powerpivot and I use an simple example of the AdventureworksDW in Powerpivot.

If i use the RELATEd function with Product and ProductSubCategory the column is empty and I expect values.

Relationships are rightfully defined. What am i doing wrong?

View 3 Replies View Related

Power Pivot :: DAX Function ALLSELECTED Doesn't Refresh When Using A Date Hierarchy For Rows

Apr 3, 2015

I've encountered an issue where the ALLSELECTED function works fine unless I use a date hierarchy, i.e. year, quarter, month, date, for the rows in a pivot and then use a year slicer, select one or more years individually, and the clear the filter on the slicer.  The year(s) that I selected in the slicer remain at 100% in the pivot instead of returning to the subtotals for the unfiltered slicer.

This only occurs when I use a calendar hierarchy for rows and a date field for the slicer, either from the hierarchy or a regular date field.Below are images of the normal behavior and then the result after following the steps above. Can't figure out why the calendar hierarchy is causing the issue since it works for all other time functions, etc., and follows best practices such as contiguous dates, etc. 

View 3 Replies View Related

Power Pivot :: LY Sales - Function Throws Error When Selecting Periods In Different Years

May 21, 2015

I have created data model where I'm taking several sources of Point of Sale data (multiple retailers) and combing them using Power Pivot and a custom calendar. We get data retailer direct, which is mostly in weeks, and data from IRI which is in four week buckets. This does not allow me to use the date intelligence DAX functions. I'm brand new to DAX and my experience starts and ends with Excel. (Diagram view and link to file to come after account verification) .

The DAX code for calculating LY Sales is:

=
CALCULATE (
    [Sales $],
    FILTER (
        ALL ( dCalendar ),
        dCalendar[IRIYearNumber]
            = VALUES ( dCalendar[IRIYearNumber] ) - 1

[Code] ....

The filters are to prevent items not on the item table from showing on the report, and the customer filter is to prevent all the sales being rolled together as and extra line (with blank customer) on the report. 

The error happens when I select two periods that are in different years. When I select the 13 periods on 2014 all is well. But when I add a period from 2015 it throws the error below;

ERROR - CALCULATION ABORTED: Calculation error in measure 'dProducts'[LY Sales $]: A table of multiple values was supplied where a single value was expected. 

View 5 Replies View Related

&"Pivot&" Function Or Analysis Service For SS2K??

Jun 7, 2007

I am relatively new to SQL-Server. I was working in a company that used SS2005. Now I am with a company and client where SS2K is my only option. I know SS2005 had Analysis Services which allowed building hypercubes but I never got the chance to learn about it or use it. I am not that familiar with what SS2K has.

I have no access to any OLAP tools. I have MS-Access and MS-Excel. My SQL-Server database has to crunch a table with thousands of rows.

Having worked with MS-Access and MS-Excel for a long time, I know how powerful creating a pivot table is. I heard that SQL2005 had a T-SQL PIVOT function but never had the opportunity to use it.

Know I have the need to do this in SQL2000.

I have a lot of data so the method shown in BOL for cross-tab won't help me. The client changes the "column" and "header" categories on a regular basis, so I need something that will allow me to NOT hard code them but choose them dynamically like one would do in a hypercube.

I have more than 5 categories for "row headers". I have currency for the data to aggregate. I have "pay periods" (26 of them) for my "column" headers, but not all 26 will be present until Dec 31, so that part has to be dynamic.


Question:
Is there any feature in the standard S2K that allows one to create anything like a pivot table without massive coding (T-SQL function or technique or something like a hypercube ability)?

Can you point me to something on the web that would explain how to get started?

Many thanks ahead of time from a newbie!

View 1 Replies View Related

Help!!! Thanks In Advance

May 29, 2001

I am new comer to SQL server. I have one question: if you have some tables need need be reviewed (maybe use "select")website visitors, what is the best way to set the permission so that the visitors can only read from the table, not have the right to change it?

thanks for any kind information.

Dsz

View 1 Replies View Related

USE When DB Name Not Known In Advance

Dec 14, 2004

NOTE: I am using MS-SQL 2K

I have a SQL script that needs to change from a particular DB to the Master DB (to grant EXECUTE permissions to a few SPs in the Master DB), then change back to the original DB. I will not know at design time what the DB name is.

What I am trying to do is something like this:


Use Master
GO
Grant EXECUTE on sp_OACreate TO C2SRolePowerUsers
GO
Declare @DBName varchar(32)
EXECUTE xp_instance_regread 'HKEY_LOCAL_MACHINE', 'SOFTWAREODBCODBC.iniMyDSNName', 'Database', @param = @DBName OUTPUT
Use @DBName
GO


The problems:

1) I have to do this in a single pass using ADO and the script. The reason is that it is part of a generic routine, looping through a list off commands, and cannot perform one command, change the DB reference via ADO, then change back in separate ADO commands.

2) It fails on the second USE command.

I have looked to see if there is some sort of "EVAL()" function, or a stored procedure to change the current DB. No luck.

Any suggestions?

Thanks,


__________________
Bob Rouse
Comsquared, Inc.

View 3 Replies View Related

Thanks In Advance

Jan 11, 2008

Can u briefly explain in which cases decimal,numeric,money datatypes is used
any difference between them and explain what is the precision and scale for those datatypes
and can u increase the precision and scale in money datatype
thank in advance

View 2 Replies View Related

Advance SQL

Jul 20, 2005

Dear Expert,How can I reuse the column, instead of select the whole things again.Example as below :selectcolumn1 as A,column2 as B,column3 * A as Cfrom dummy ;in MS SQL I have to do like this,selectcolumn1 as A,column2 as B,column3 * column1 as Cfrom dummy ;ThanksDesmond

View 2 Replies View Related

Please Help! Thanks In Advance

Nov 25, 2007

I'm doing a shopping cart using SQL Express and Visual Studio Web Developer on C#, ASP.NET

I recieved error when adding a order:
The variable name '@oid' has already been declared. Variable names must be unique within a query batch or stored procedure.
The codes are:
comm = new SqlCommand("SELECT IDENT_CURRENT('Orders') as NewOrderID ");

comm.Connection = conn;
comm.Transaction = myTrans;

OrderID = Convert.ToInt32(comm.ExecuteScalar());

foreach (CartItem i in o.ItemList)
{
comm.CommandText = "INSERT INTO OrderDetail(OrderID, ProductID, Quantity, UnitPrice)VALUES (@oid, @pid, @qty, @price)";

comm.Parameters.AddWithValue("@oid", OrderID);
comm.Parameters.AddWithValue("@pid", i.ProductID);
comm.Parameters.AddWithValue("@qty", i.Quantity);
comm.Parameters.AddWithValue("@price", i.UnitPrice);
comm.Connection = conn;
comm.Transaction = myTrans;
comm.ExecuteNonQuery();
}

It seems that i can't add records into database with multiple loop.

Thanks in advance.

View 10 Replies View Related

Sql2005 Database Restore From Another Sql2005 Backup File Error.

Dec 15, 2005

hi

i try to restore a bak file from another sql2005 server to my sql2005 server, but it show the error message as below :

 

 

TITLE: Microsoft SQL Server Management Studio Express
------------------------------

An exception occurred while executing a Transact-SQL statement or batch. (Microsoft.SqlServer.Express.ConnectionInfo)

------------------------------
ADDITIONAL INFORMATION:

Cannot open backup device 'C:Program FilesMicrosoft SQL ServerMSSQL.1MSSQLBackupackup.bak'. Operating system error 5(error not found).
RESTORE HEADERONLY is terminating abnormally. (Microsoft SQL Server, Error: 3201)

For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer=09.00.1399&EvtSrc=MSSQLServer&EvtID=3201&LinkId=20476

------------------------------
BUTTONS:

OK
------------------------------


 

 

 

pls some one can help me ???

 

thanks

chaus

View 62 Replies View Related

Can You Open A Database Created In SQL2005 In SQL2005 Express?

Oct 12, 2007



Can you open/use a database created in SQL2005 in SQL2005 Express?

Thanks for the help!

Max

View 4 Replies View Related

Advance Programmers Only

Jan 6, 2004

hi ,
I am using ASP.NET with SQL Server. I have a function ABC() which creates,open ,and then dispose sqlserver's connection .
I am using ABC() twice in one .aspx page ,my friend who build this function argued that this function will open only one connection in everypage ,no matter how many times we call function ABC() in a single page ,while i denies .
Please tell me ,because our whole company database acces relies on this single ABC() function.

Thanks in Advance

View 2 Replies View Related

Advance SQL Question

Jul 23, 2005

Hello everybody,i have a advance question about a specific sql problem:My table A have for example 3 columns.in the third column are words seperated by ~.ID COL2 COL3--------------1 ab test~dummy~ddd2 cd testdata2~sjhfdg~sdf3 ef sd~test4 gh sd~cvNow i want two lists:1.) used Values for column 3:Values------testdummydddtestdata2sjhfdgsdfsdcv2.) used values plus IDValue ID----------test 1test 3sd 3sd 4cv 4dummy 1....Is it posible to produce such a list with nearly one SQL -Statement or withtemporaly tables ?Thanks in advanceT.KindermannDatabase Administrator----------------------------------------------------------------------------Thomas KindermannE-MAIL: Reply to TKINDER<x>@GMX.DE without <x>

View 2 Replies View Related

Advance ORDER BY

Jul 20, 2005

Hi,I'm wondering if there's any advance order by 'function'/workaround,which is reasonably efficient for MS SQL Server, without resorting tosome third party indexing/search engine to achieve the following.The mechanism is to record each instance of a pattern match and orderby rows with most matches first (DESC). Simplistic match but that's aseparate issue.Sample:create table tmp (col varchar(50));insert into tmpvalues ('a barking dog');insert into tmpvalues ('a dog and cat fights over dog food');insert into tmpvalues ('lovable dog is not barking dog=nice dog');The goal for the Sample is to return resultsets in the followingorder:lovable dog is not barking dog=nice dog -- 3 matchesa dog and cat fights over dog food -- 2 matchesa barking dog -- 1 matchThanks.

View 6 Replies View Related

Advance Tab Not Available (Greyed Out)

Jan 27, 2007

 

Hello I am working on a sql express table and while configuring the steps after I select the data source and the selectment statement window shows, I want to use the advanced tab but it is greyed out. I want to be able to add edit and delete my data. I have administrator rights for this project and the workstation so thats not the issue. What I am tryng to accomplish is extending a website to manage it's content and users. Also the table has colums and the colums has test data within them I tested a query and the connection had a successful return. Maybe it's a configuration thing I am unaware of.

 

DKB 

View 3 Replies View Related

SQL Express Advance

Aug 24, 2007

Does SQL Express Advanced allow remote connections or do I have to have SQL Express installed on each computer and attach the MDF in order for other people to use a database.

I have a database that is not large but the JET engine in Access runs too slow for the data that I have. The SQL Express engine is more robust and returns the queries much faster than Access, especially when I am dealing with tables that contain a million records. I don't want to get into using the resources of a server for this task. I installed SQL Express Adv and would like to use my computer as host for the database but I cannot connect to the instance even when I open the computer, grant permission etc...

I know that SQL Express typically does not allow remotes connections but I thought maybe the advance version may. Your assistance is greatly appreciated.

View 3 Replies View Related

SQL Problem - Any Suggestions. Thx In Advance.

Jul 20, 2006

Hi
Any help with this would be greatly appreciated.
I have two tables
First Table is called "Team" see columns and data below
TeamId, TeamName, MemberId
1, White Team, 1
2, Grey Team, Null
 
Second Table is called "Members" see columns and data below
MemberId, Name
1, Jim Smith
 
I want to display both tables in a gridview as follows
TeamId, TeamName, MemberId, Name
1, White Team, 1, Jim Smith
2, White Team , Null, Null
 
I'm using the following sql procedure to do this
 
Select
Team.TeamId,
Team.TeamName,
Team.MemberId,
Meember.Name
From Team
Inner Join Members on Members.MemberId = Team.MemberId
 
My Problem is that this select statement returns the first row but not the second row. The reason for this is the second row's memberId is Null. However, I still need to display this row even if the data is some of the data is null.
Can anyone point out the correct sql statement for this?
 

View 1 Replies View Related

Advance Problem , Just For The Expeirinces

Apr 3, 2007

Forbidden
You don't have permission to access /localhost:8080/sas/(S(b2vekk55equugyjebolothq0))/Main1.aspx on this server.







what is the solution ????

View 1 Replies View Related

Upgraded SQL2000 To SQL2005, SQL2005 VERY Slow

Dec 27, 2005

I just upgraded my SQL 2000 server to SQL2005. I forked out all that money, and now it takes 4~5 seconds for a webpage to load. You can see for yourself. It's pathetic. When I ran SQL2000, i was getting instant results on any webpage. I can't find any tool to optimize the tables or databases. And when I used caused SQL Server to use 100% cpu and 500+MB of ram. I can't have this.Can anyone give me some tips as to why SQL 2005 is so slow?

View 3 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved