Showing posts with label named. Show all posts
Showing posts with label named. Show all posts

Friday, March 30, 2012

Help with SQL Query

Hello Everyone,

I need help writing this query. I have a table named "PMP" that stores up to 10 objective ID's:

Code Snippet

SELECT ObjectiveID1,ObjectiveID2,ObjectiveID3,ObjectiveID4,... ObjectiveID10

FROM PMP

WHERE PMPID = @.PMPID

I have a child table named "METRICS" that stores the details for each objective:

Code Snippet

SELECT ObjectiveID, TitleText, Description, KPIvalue

FROM METRICS

WHERE ObjectiveID IN (query the PMP table)

I need to write a query that will return all the Metrics that are used for a given PMPID. Any ideas how this can be done?

Thank You

My first suggestion is to correct a bad design mistake. You have a severly de-normalized table.

You most likely 'should' NOT have columns Objective1-Objective10.

You most likely would benefit from having a separate table for Objectives.

THEN issues such as this one would become MUCH easier to solve.

If you are using SQL 2005, you may find the UNPIVOT statement to be useful.

|||

Which version of SQL Server are you using?

AMB

|||

I am using SQL Server 2005 Express Edition

I understand why you would think this table is de-normalized, but it's the right structure for the solution. My organization allows a maximum of 10 objectives to be identified per request. I need to send my crystal report 1 record.

Can someone help me with the UNPIVOT query?

Thank You

|||

I figured it out:

SELECT * FROM COACHING.METRICS

WHERE OBJECTIVEID IN (

SELECT OBJECTIVEID

FROM

(SELECT RESULT1_OBJECTIVEID,

RESULT2_OBJECTIVEID,

RESULT3_OBJECTIVEID,

RESULT4_OBJECTIVEID,

RESULT5_OBJECTIVEID,

RESULT6_OBJECTIVEID,

RESULT7_OBJECTIVEID,

RESULT8_OBJECTIVEID,

RESULT9_OBJECTIVEID,

RESULT10_OBJECTIVEID

FROM COACHING.PMPFORMS

WHERE PMPID = 271 ) OBJ

UNPIVOT

(OBJECTIVEID FOR PMPID IN (RESULT1_OBJECTIVEID,

RESULT2_OBJECTIVEID,

RESULT3_OBJECTIVEID,

RESULT4_OBJECTIVEID,

RESULT5_OBJECTIVEID,

RESULT6_OBJECTIVEID,

RESULT7_OBJECTIVEID,

RESULT8_OBJECTIVEID,

RESULT9_OBJECTIVEID,

RESULT10_OBJECTIVEID)) VALS)

|||
Thanks Arnie Rowland and hunchback for your reponses
|||I'm glad we could point you in a direction that worked.sql

Wednesday, March 28, 2012

Help with SQL

I have a table named "policy_details" having four columns called policy_details(varchar),effectdate(datetime),Historyid(int) and policy_status(varchar).

I want to keep only the maximum historyid records in "policy_details" where policy_details and effectdate should be equal and policy_status should be '30240084' . I want to delete the remaining records where policy_details and effectdate should be equal and policy_status should be '30240084'.

Cheers

Praveen

So if you order by policy_details ASC, affectdate ASC, historyid DESC then you only want to keep the first row from each (policy_details, affectdate) group.

I would use the ROW_NUMBER() function and delete where it's not 1

DELETE
FROM policy_details
WHERE ROW_NUMBER() OVER ( PARTITION BY policy_details, affectdate
ORDER BY historyid DESC
) > 1
AND policy_status = '30240084'

|||

Adam,

Thanks for your query.

I am getting an error "The ranking function "ROW_NUMBER" must have an ORDER BY clause."

One more thing is i want same effectdate with only date but not time part.

DELETE
FROM policy_details
WHERE ROW_NUMBER() OVER ( PARTITION BY policy_details,CONVERT(CHAR(10),effectdate,103)
ORDER BY historyid DESC
) > 1
AND policy_status = '30240084'

I did not understand "The ranking function "ROW_NUMBER" must have an ORDER BY clause" error though it is having order by clause. Any ideas?

Cheers

Praveen

|||

Use A CTE, it will work:

WITH myCTE

AS

(SELECT ROW_NUMBER() OVER ( PARTITION BY policy_details,CONVERT(CHAR(10),effectdate,103) ORDER BY historyid DESC) as num

FROM policy_details

WHERE policy_status = '30240084')

DELETE FROM myCTE WHERE num>1

|||

Interesting, when I write the following query, which is almost exactly like yours:

begin transaction

DELETE
FROM person.address
WHERE ROW_NUMBER() OVER ( PARTITION BY addressId
ORDER BY addressLine1 DESC
) > 1
and addressLine1 = 'fred'
rollback transaction

The error I get is:

Msg 4108, Level 15, State 1, Line 3
Windowed functions can only appear in the SELECT or ORDER BY clauses.

(which is more clear).

|||Hello,
After some research, I tested out this syntax which works:
DELETE c
FROM (SELECT * FROM (SELECT RANK() OVER (PARTITION BY policy_details,CONVERT(CHAR(10),effectdate,103) ORDER BY historyid DESC) as num
FROM policy_details WHERE policy_status = '30240084' ) AS t
WHERE t.num>1) c|||

Hi Limno,

Thanks for your help with the SQL which works fine with my data.

I have written a small strored proc which deletes some data based on certain criteria which works fine but it takes approximately 30 minutes for one million records. Is there any way to write this stored proc logic into a single SQl query or sub queries?

The SP is :

-- ***********************************************************************

declare @.policy_details_id uniqueidentifier

declare @.Prepolicy_details_id uniqueidentifier

declare @.EffectDate datetime

declare @.CloseDate datetime

declare @.historyid int

DECLARE DATECur CURSoR FOR

select distinct(policy_details_id),effectdate,closedate,historyid from SM_Cust_policy_Details

where closedate = '2079-06-06 00:00:00.000' and derivative = 0

order by policy_details_id,effectdate

OPEN DATECur

FETCH NEXT FROM DATECur INTO @.policy_details_id, @.effectdate,@.CloseDate,@.historyid

WHILE @.@.FETCH_STATUS = 0

BEGIN

DELETE SM_Cust_policy_details where policy_details_id=@.policy_details_id

and historyid <> @.historyid

and closedate <> '2079-06-06 00:00:00.000'

and CONVERT(DATETIME,CONVERT(CHAR(10),effectdate,103)) >= CONVERT(DATETIME,CONVERT(CHAR(10),@.effectdate,103))

and policy_status_id = 30240084

and derivative = 0

FETCH NEXT FROM DATECur INTO @.policy_details_id, @.effectdate,@.CloseDate,@.historyid

END

CLOSE DATECur

DEALLOCATE DATECur

-- ***********************************************************************

Once again thanks for your help..

Cheers

Praveen

|||Can you explain what the query is trying to do in english rather than trying to decode your criteria. The potential query may differ depending the nature of the data in your table e.g. uniqueness and nullability of the columns.|||

Hi

I need to delete the table data based on the following criteria.

1) "policy_details_id" should be same

2) "effectdate" is greater than or equal to effectdate

3) "HistoryId" should not be same

4) "closedate" is not equal to ' 2079-06-06 00:00:00.000 '

5) "policy_status_id" should be 30240084

6) "Derivative" should be 0

Cheers

Praveen

|||

I can read your code. I got that much from the stored proc you posted. I'm trying to understand what the stored procedure is trying to achieve.

Should just one row per policy_details_id remain after the delete? Why are you doing distinct of the policy_details_id in you cursor query? why delete where effectdate is greater than @.effectdate? Wouldn't that delete more recent rows.

Like I said, I'm trying to understand what this query is doing "in english" and not "in SQL". An explanation similar to your original posting is what I'm after.

|||

Hi Adam,

Thanks for your reply and here are the answers for your queries.

******** Should just one row per policy_details_id remain after the delete?

Yes, I want to keep only one row per policy_details_id after the deletion.

****** Why are you doing distinct of the policy_details_id in you cursor query?

I used distinct caluse in order to reduce the cursor result set in stored proc. Anyway you can avoid distinct caluse in the sql query.

******** why delete where effectdate is greater than @.effectdate? Wouldn't that delete more recent rows

Yes, it is going to delete more recent rows.

Cheers

Praveen

|||

Hello:

Please check this query :

DELETE c

FROM (SELECT * FROM (SELECT *, RANK() OVER (PARTITION BY policy_details_id ORDER BY historyid DESC, effectdate) as num

FROM policy_details WHERE (closedate<> '2079-06-06 00:00:00.000' OR closedate is NULL) AND Derivative=0 AND policy_status_id = 30240084 ) AS t

WHERE t.num>1) c

|||

Hi Limno,

Needs to change the query.

First i need to do the following query..

1) select policy_details_id,effectdate,closedate,historyid from SM_Cust_policy_Details where closedate = '2079-06-06 00:00:00.000' and derivative = 0

Based on the result set of this query i need to do the following delete query.

2) DELETE SM_Cust_policy_details where policy_details_id = resultset_policy_details_id and historyid <> resultset_historyid and closedate <> '2079-06-06 00:00:00.000' and CONVERT(DATETIME,CONVERT(CHAR(10),effectdate,103))>=CONVERT(DATETIME,CONVERT(CHAR(10),resultset_effectdate,103)) and policy_status_id=30240084 and derivative = 0.

Note: resultset_policy_details_id,resultset_historyid,resultset_effectdate are the result set query values of policy_details_id,historyid,effectdate in query number 1.

How can i integrate both of the above queries and make a single query?

Cheers

Praveen

|||

Could you post a set of your sample data in your table and the expected result? Thanks.

|||

The data consists like this..

policy_details_id policy_status_id historyid effectdate closedate

70C36E97-9564-A048-0000-9665018B81FF 30240084 9 2004-09-11 12:00:00.000 2004-10-11 11:34:00.000
70C36E97-9564-A048-0000-9665018B81FF 30240084 10 2004-10-11 11:34:00.000 2005-09-11 11:47:00.000
70C36E97-9564-A048-0000-9665018B81FF 30240084 11 2005-09-11 12:00:00.000 2005-09-11 12:00:00.000
70C36E97-9564-A048-0000-9665018B81FF 14075352 12 2005-09-11 11:47:00.000 2079-06-06 00:00:00.000

First i need to consider the effectdate where closedate is '2079-06-06 00:00:00.000'.In this case it is '2005-09-11 11:47:00.000'.

I need to delete the records where effectdate(only datepart) is equal or greater than '2005-09-11' and policy_status_id should be 30240084.

In the above case the third record i.e historyid = 11 is going to be deleted.

Let me know if you have any problems to understand.

Cheers

Praveen

Wednesday, March 21, 2012

help with reporting services

I installed sql express with advanced services on a local network computer named 'Tester'. For service accounts I used 'network service' and 'mixed mode' for authentication. I would like to publish database reports using reporting services. when i open a web browser on the machine with sql express and type in the url: http://localhost/reports or http://localhost/reportserver the web pages work fine. but when i go to a different machine thats on the same network and use the url: http://Tester/reports or http://Tester/reportserver the web page is not found. how do i get users on the network to be able to view the virtual report server directories on the Tester computer? Help would be greatly appreciated.

Hi,

did you check your IIS configuration of your localhost (Tester)?

Is there an alias for your network computer - "Tester", DNS?

Have you put in a Hostheadername by IP?

What about a ping`?

Have you test http://172.../reports ?

CU

tosc

|||i can ping 'Tester' fine, i've tried http://<ip of host>/reports. IIS is configured for integrated windows autentication. I tried setting authentication to allow anonymous access but that didnt work either.|||

Hi John,

by installation, have you check "Use SSL..." checkbox in the installation wizard?

CU

tosc

|||

are you referring to the install of IIS? I dont recall, should I try to reinstall IIS?

Thanks,

John

|||

Hi John,

NO, i'm referring to Installing and Configuring SQL Server Reporting Services!

Have yopu check "Use SSL..." checkbox in the installation wizard?

CU

tosc

|||

Hi John,

Unless you changed it manually, Reporting Services is given an instance name just like the database service. Try adding "$SQLEXPRESS" (without quotes) to the end of your URL. Needless to say, if you installed to a different instance name, use that inplace of SQLEXPRESS.

Mike

|||I've tried all the url's and none of them work. Does IIS have to be configured in a particular way? also do I need to add permissions to my report server database? I would think that anyone on the intranet who knows the host computer name can put in the url and view the reportserver web page. Im not getting prompted for a login, my web browser just says the page cannot be displayed, that makes me think that it is network problem and not a configuration problem on the local machine.|||

I have had similar troubles. I have a report server configured on a computer on the network. I've installed SQL Express 2005 and the toolkits to get hold of RS. The computer is running IIS 5 and is connected using MMC. Reports can be generated, deployed, and viewed using a browser and URL from this machine quite happily.

However, when I try to access the report server from a different computer on the network I also get a

Internet Explorer cannot display the webpage

message.

I have tried:

http://rs_name/reports

http://rs_name.network.local/reports

http://rs_name/reports$sqlexpress

I can ping the machines from eachother successfully and I have made profiles from within Report Manager for each user on these machines. Is this a Express thing? SURELY, you must be able to access these reports across a Windows network.

Many thanks.

Leslie

|||

You sould ask this question in the Report Services forum to get a better answer. (http://forums.microsoft.com/MSDN/ShowForum.aspx?ForumID=82&SiteID=1)

Mike

|||

OK. I'll ask them over there. Thank you very much, and apoligies for being in the wrong place.

L

help with reporting services

I installed sql express with advanced services on a local network computer named 'Tester'. For service accounts I used 'network service' and 'mixed mode' for authentication. I would like to publish database reports using reporting services. when i open a web browser on the machine with sql express and type in the url: http://localhost/reports or http://localhost/reportserver the web pages work fine. but when i go to a different machine thats on the same network and use the url: http://Tester/reports or http://Tester/reportserver the web page is not found. how do i get users on the network to be able to view the virtual report server directories on the Tester computer? Help would be greatly appreciated.

Hi,

did you check your IIS configuration of your localhost (Tester)?

Is there an alias for your network computer - "Tester", DNS?

Have you put in a Hostheadername by IP?

What about a ping`?

Have you test http://172.../reports ?

CU

tosc

|||i can ping 'Tester' fine, i've tried http://<ip of host>/reports. IIS is configured for integrated windows autentication. I tried setting authentication to allow anonymous access but that didnt work either.|||

Hi John,

by installation, have you check "Use SSL..." checkbox in the installation wizard?

CU

tosc

|||

are you referring to the install of IIS? I dont recall, should I try to reinstall IIS?

Thanks,

John

|||

Hi John,

NO, i'm referring to Installing and Configuring SQL Server Reporting Services!

Have yopu check "Use SSL..." checkbox in the installation wizard?

CU

tosc

|||

Hi John,

Unless you changed it manually, Reporting Services is given an instance name just like the database service. Try adding "$SQLEXPRESS" (without quotes) to the end of your URL. Needless to say, if you installed to a different instance name, use that inplace of SQLEXPRESS.

Mike

|||I've tried all the url's and none of them work. Does IIS have to be configured in a particular way? also do I need to add permissions to my report server database? I would think that anyone on the intranet who knows the host computer name can put in the url and view the reportserver web page. Im not getting prompted for a login, my web browser just says the page cannot be displayed, that makes me think that it is network problem and not a configuration problem on the local machine.|||

I have had similar troubles. I have a report server configured on a computer on the network. I've installed SQL Express 2005 and the toolkits to get hold of RS. The computer is running IIS 5 and is connected using MMC. Reports can be generated, deployed, and viewed using a browser and URL from this machine quite happily.

However, when I try to access the report server from a different computer on the network I also get a

Internet Explorer cannot display the webpage

message.

I have tried:

http://rs_name/reports

http://rs_name.network.local/reports

http://rs_name/reports$sqlexpress

I can ping the machines from eachother successfully and I have made profiles from within Report Manager for each user on these machines. Is this a Express thing? SURELY, you must be able to access these reports across a Windows network.

Many thanks.

Leslie

|||

You sould ask this question in the Report Services forum to get a better answer. (http://forums.microsoft.com/MSDN/ShowForum.aspx?ForumID=82&SiteID=1)

Mike

|||

OK. I'll ask them over there. Thank you very much, and apoligies for being in the wrong place.

L

Monday, March 12, 2012

Help with Query

Hi Everyone,

I need help writing the following query. I have a table named DeptHistory that stores an employee's department history:

DeptHistory [DeptID(pk),EmpID(fk),StartDate,EndDate]

(EndDate will be NULL for the current department)

I need to write a query that will return all the department that employee was in between Jan 2007 to Jun 2007

Example:

--

Employee Name: Sam Costa

Service Dept 5/1/2006 - 12/5/2006

Parts Dept 12/6/2006 - 3/1/2007

Dispatch Dept 3/2/2007 - NULL

--

So the query should return Parts Dept and Dispatch Dept

Thank You,

-Sam

Code Snippet

select DeptID

from DeptHistory dh

where isnull(year(EndDate), 2007) = 2007

and EmpID = 1

|||

Hi DaleJ,

Thank you for your response. The query you provided does not check which depts the employee was in for a specifed date range.

|||

Well, If the end date isn't in 2007 (or null) then they weren't in that dept between jan 2007 and jun 2007.

|||

try the following query..

Code Snippet

Create Table #data (

[Dept] Varchar(100) ,

[SDate] datetime ,

[EDate] datetime

);

Insert Into #data Values('Service Dept','5/1/2006','12/5/2006');

Insert Into #data Values('Parts Dept','12/6/2006','3/1/2007');

Insert Into #data Values('Dispatch Dept','3/2/2007',NULL);

Select * From #Data

Where

SDate between '01/01/2007' and '6/30/2007'

or EDate between '01/01/2007' and '6/30/2007'

|||

what if an employee was employeed at a dept for the entire duration?

Code Snippet

Select * From #Data

Where

SDate between '01/01/2007' and '6/30/2007'

or isnull(EDate, getdate()) between '01/01/2007' and '6/30/2007'

or (SDate < '01/01/2007' and isnull(EDate, getdate()) > '6/30/2007')

also... for each end date, you'll have to check for null.

|||

As the approach below demonstrates, it is only necessary to determine if someone's StartDate is before the end of the period, and that their EndDate was sometime after the beginning of the period. (The current date is substitued for the NULL values.)

Code Snippet


SET NOCOUNT ON


DECLARE @.DeptHistory table
( RowID int IDENTITY,
DeptID int,
EmpID int,
StartDate smalldatetime,
EndDate smalldatetime
)


DECLARE @.Employee table
( EmpID int IDENTITY,
EmpName varchar(20)
)


DECLARE @.Department table
( DeptID int IDENTITY,
DeptName varchar(20)
)


INSERT INTO @.Employee VALUES ( 'Sam Costa' )
INSERT INTO @.Employee VALUES ( 'Bilbo Baggins' )


INSERT INTO @.Department VALUES ( 'Service' )
INSERT INTO @.Department VALUES ( 'Parts' )
INSERT INTO @.Department VALUES ( 'Dispatch' )


INSERT INTO @.DeptHistory VALUES ( 1, 1, '5/1/2006', '12/5/2006' )
INSERT INTO @.DeptHistory VALUES ( 1, 2, '5/1/2006', NULL )
INSERT INTO @.DeptHistory VALUES ( 2, 1, '12/6/2006', '3/1/2007' )
INSERT INTO @.DeptHistory VALUES ( 3, 1, '3/2/2007', NULL )


SELECT
d.DeptName,
e.EmpName,
h.StartDate,
h.EndDate
FROM @.DeptHistory h
JOIN @.Employee e
ON h.EmpID = e.EmpID
JOIN @.Department d
ON h.DeptID = d.DeptID
WHERE ( h.StartDate < '2007/07/01'
AND isnull( h.EndDate, getdate() ) >= '2007/01/01'
)


DeptName EmpName StartDate EndDate
-- -- -- -
Service Bilbo Baggins 2006-05-01 NULL
Parts Sam Costa 2006-12-06 2007-03-01
Dispatch Sam Costa 2007-03-02 NULL

(Output edited for display.)

Wednesday, March 7, 2012

Help with nonempty crossjoin....

Hello...

i have made a calculated measure named [Location Count] that has this expression:

NONEMPTYCROSSJOIN(descendants([dimTargetSet].currentmember, 9, LEAVES),descendants([dimLocation].currentmember,9,LEAVES)).count

In AS it seems to be working but when I call the measure in my query in reporting services it always returns zero. what am i doing wrong here?...

WITH SET [Locations] AS '{[dimlocation].&[2583]}' MEMBER [Measures].[Section Count] AS '[dimQuestionSection].&[323].children.count' MEMBER [dimSurveyQuestion].[Audits] AS 'Aggregate ({[dimSurveyQuestion].&[323]})' SELECT {[Measures].[Location Count]} ON COLUMNS, {FILTER(CROSSJOIN(DESCENDANTS([Locations],1,LEAVES), DESCENDANTS([dimQuestionSection].&[323],1)), [Measures].[Last Audited Date]>0)} ON ROWS FROM cubeAuditTargetSet WHERE ([dimSurveyQuestion].[Audits], [dimDate].&[2007], [dimUser].&[323], [dimTargetSet].&[323].&[9])

Could be because you're using a calculated member: [dimSurveyQuestion].[Audits] in the where clause. Does it work if you replace it with the actual member?|||

thanks for your reply... actually i need to use aggregate with [dimSurveyQuestion].[Audits] because there are instance we search for three members of the dimension...

MEMBER [dimSurveyQuestion].[Audits] AS 'Aggregate ({[dimSurveyQuestion].&[323].&[1], dimSurveyQuestion].&[323].&[2], dimSurveyQuestion].&[323].&[3]})'

any idea?... thanks...

Help with nonempty crossjoin....

Hello...

i have made a calculated measure named [Location Count] that has this expression:

NONEMPTYCROSSJOIN(descendants([dimTargetSet].currentmember, 9, LEAVES),descendants([dimLocation].currentmember,9,LEAVES)).count

In AS it seems to be working but when I call the measure in my query in reporting services it always returns zero. what am i doing wrong here?...

WITH SET [Locations] AS '{[dimlocation].&[2583]}' MEMBER [Measures].[Section Count] AS '[dimQuestionSection].&[323].children.count' MEMBER [dimSurveyQuestion].[Audits] AS 'Aggregate ({[dimSurveyQuestion].&[323]})' SELECT {[Measures].[Location Count]} ON COLUMNS, {FILTER(CROSSJOIN(DESCENDANTS([Locations],1,LEAVES), DESCENDANTS([dimQuestionSection].&[323],1)), [Measures].[Last Audited Date]>0)} ON ROWS FROM cubeAuditTargetSet WHERE ([dimSurveyQuestion].[Audits], [dimDate].&[2007], [dimUser].&[323], [dimTargetSet].&[323].&[9])

Could be because you're using a calculated member: [dimSurveyQuestion].[Audits] in the where clause. Does it work if you replace it with the actual member?|||

thanks for your reply... actually i need to use aggregate with [dimSurveyQuestion].[Audits] because there are instance we search for three members of the dimension...

MEMBER [dimSurveyQuestion].[Audits] AS 'Aggregate ({[dimSurveyQuestion].&[323].&[1], dimSurveyQuestion].&[323].&[2], dimSurveyQuestion].&[323].&[3]})'

any idea?... thanks...