Showing posts with label following. Show all posts
Showing posts with label following. Show all posts

Friday, March 30, 2012

how to excluded the intersection of 2 dimensions ?

Hi,

I have the following simplified problem.

I have a fact table and two dimension tables, colors and weekdays.

I can make a query to select all except red and all except on monday but I like to make a query to select all except red mondays ?

They query tool doesn't give you really the options.

Any suggestions ?

Constantijn Enders

You can do it in MDX, but only a few query tools will allow you to construct queries like this. I think vendors tend to refer to this capability as 'asymmetic sets'; I can only think of one tool I've seen recently that did this (Intelligencia - http://www.it-workplace.co.uk/i4wfeatures.aspx) but I'm sure that if you hunt around there will be others. Does anyone else know of one?

Here's an MDX query to prove it's possible:

select

measures.[internet sales amount] on 0,

except(

[Date].[Day Name].[Day Name].members

*

[Product].[Color].[Color].members

,{([Date].[Day Name].&[2], [Product].[Color].&[Red])}

) on 1

from [Adventure Works]

HTH,

Chris

Wednesday, March 28, 2012

How to enfore a primary key range ??

I've inherited the following situation...
The table contains 4 columns... script below
Note that the first 3 columns denote the primary Key...
Actually what is really meant is the following...
Let's say the values for one row are as follows...
Code= A
LowVal = 25
HighVal=50
UseThis=Fred
What they want to be implied by this row... if Code=A and the test val is
between 25 and 50 UseThis= Fred
They want to disallow any row that overlaps from being added... such as the
following...
Code= A
LowVal = 30
HighVal=40
UseThis=Joe
How can you enforce something like this ?
CREATE TABLE [dbo].[Table1] (
[Code] [char] (10) COLLATE Latin1_General_BIN NOT NULL ,
[LowVal] [decimal](6, 0) NOT NULL ,
[HighVal] [decimal](6, 0) NOT NULL ,
[UseThis] [char] (10) COLLATE Latin1_General_BIN NULL
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[Table1] ADD
CONSTRAINT [PK_Table1] PRIMARY KEY CLUSTERED
(
[Code],
[LowVal],
[HighVal]
) ON [PRIMARY]"Rob" <rwchome@.comcast.net> wrote in message
news:l4WdnX_h78I-eyzeRVn-vA@.comcast.com...
> I've inherited the following situation...
> The table contains 4 columns... script below
> Note that the first 3 columns denote the primary Key...
> Actually what is really meant is the following...
> Let's say the values for one row are as follows...
> Code= A
> LowVal = 25
> HighVal=50
> UseThis=Fred
> What they want to be implied by this row... if Code=A and the test val is
> between 25 and 50 UseThis= Fred
> They want to disallow any row that overlaps from being added... such as
> the following...
> Code= A
> LowVal = 30
> HighVal=40
> UseThis=Joe
> How can you enforce something like this ?
>
> CREATE TABLE [dbo].[Table1] (
> [Code] [char] (10) COLLATE Latin1_General_BIN NOT NULL ,
> [LowVal] [decimal](6, 0) NOT NULL ,
> [HighVal] [decimal](6, 0) NOT NULL ,
> [UseThis] [char] (10) COLLATE Latin1_General_BIN NULL
> ) ON [PRIMARY]
> GO
> ALTER TABLE [dbo].[Table1] ADD
> CONSTRAINT [PK_Table1] PRIMARY KEY CLUSTERED
> (
> [Code],
> [LowVal],
> [HighVal]
> ) ON [PRIMARY]
>
You'll have to use a trigger for this, eg:
create trigger Table1_no_overlap
on Table1 for insert, update
as
begin
if exists
(
select *
from Table1 l
join Table1 r
on l.LowVal < r.LowVal
and l.HighVal > r.LowVal
)
begin
raiserror('Change would create overlapping range.',16,1)
rollback transaction
end
end
David|||Thanks David,
Maybe I am doing something wrong, but I was able to add the following rows
after applying the trigger...
insert into Table1 Values('A',20,100,'Joe')
insert into Table1 Values('A',20,500,'FRED')
Rob
"David Browne" <davidbaxterbrowne no potted meat@.hotmail.com> wrote in
message news:eDxVWD1CGHA.344@.TK2MSFTNGP11.phx.gbl...
> "Rob" <rwchome@.comcast.net> wrote in message
> news:l4WdnX_h78I-eyzeRVn-vA@.comcast.com...
> You'll have to use a trigger for this, eg:
> create trigger Table1_no_overlap
> on Table1 for insert, update
> as
> begin
> if exists
> (
> select *
> from Table1 l
> join Table1 r
> on l.LowVal < r.LowVal
> and l.HighVal > r.LowVal
> )
> begin
> raiserror('Change would create overlapping range.',16,1)
> rollback transaction
> end
> end
>
> David
>|||Hi, Rob
Use the following trigger:
alter trigger Table1_no_overlap
on Table1 for insert, update
as
begin
if exists
(
select *
from Table1 t
join inserted i
on t.LowVal between i.LowVal and i.HighVal
or i.LowVal between t.LowVal and t.HighVal
where i.Code<>t.Code or i.LowVal<>t.LowVal or i.HighVal<>t.HighVal
)
begin
raiserror('Change would create overlapping range.',16,1)
rollback transaction
end
end
If you want to allow overlapping ranges for different codes (but not
for the same code), the trigger would be like this:
alter trigger Table1_no_overlap
on Table1 for insert, update
as
begin
if exists
(
select *
from Table1 t
join inserted i
on t.Code=i.Code and (
t.LowVal between i.LowVal and i.HighVal
or i.LowVal between t.LowVal and t.HighVal
)
where i.LowVal<>t.LowVal or i.HighVal<>t.HighVal
)
begin
raiserror('Change would create overlapping range.',16,1)
rollback transaction
end
end
Razvan|||Rob wrote:

> Thanks David,
> Maybe I am doing something wrong, but I was able to add the following rows
> after applying the trigger...
> insert into Table1 Values('A',20,100,'Joe')
> insert into Table1 Values('A',20,500,'FRED')
> Rob
>
Try it like this. Notice that I've added an extra constraint, modified
the join in the trigger and added CODE to the join. That's my reading
of what you want to achieve. Test carefully.
ALTER TABLE table1 ADD CONSTRAINT ck_table1_lowval_highval
CHECK (lowval <= highval) ;
GO
create trigger Table1_no_overlap
on Table1 for insert, update
as
begin
if exists
(
select *
from Table1 l
join Table1 r
on l.LowVal < r.HighVal
and l.HighVal > r.LowVal
and l.code = r.code
)
begin
raiserror('Change would create overlapping range.',16,1)
rollback transaction
end
end
GO
David Portas
SQL Server MVP
--|||Hi, David
Your trigger doesn't allow any row to be inserted.
Razvan|||Razvan Socol wrote:
> Hi, David
> Your trigger doesn't allow any row to be inserted.
> Razvan
You're right. Here's a correction:
create trigger Table1_no_overlap
on Table1 for insert, update
as
begin
if exists
(
select *
from Table1 l
join Table1 r
on l.LowVal < r.HighVal
and l.HighVal > r.LowVal
and l.code = r.code
and (l.LowVal <> r.LowVal
or l.HighVal <> r.HighVal)
)
begin
raiserror('Change would create overlapping range.',16,1)
rollback transaction
end
end
GO
David Portas
SQL Server MVP
--|||Hi, David
My understanding of the original post is that the following rows are
not allowed (but your trigger allows them):
insert into Table1 Values('A',20,100,'Joe')
insert into Table1 Values('A',100,150,'FRED')
Rob wrote:
> What they want to be implied by this row... if Code=A and the test val is
> between 25 and 50 UseThis= Fred
The following rows would be ok:
insert into Table1 Values('A',20,100,'Joe')
insert into Table1 Values('A',101,150,'FRED')
Razvan|||Thank you both Razvan and David...
Sorry I was not clear on this, actually same HighVal on one row may be equal
to LowVal on another...
The code applied uses > LowVal and <= HighVal...
Rob
"Razvan Socol" <rsocol@.gmail.com> wrote in message
news:1135755688.241085.105660@.g49g2000cwa.googlegroups.com...
> Hi, David
> My understanding of the original post is that the following rows are
> not allowed (but your trigger allows them):
> insert into Table1 Values('A',20,100,'Joe')
> insert into Table1 Values('A',100,150,'FRED')
> Rob wrote:
> The following rows would be ok:
> insert into Table1 Values('A',20,100,'Joe')
> insert into Table1 Values('A',101,150,'FRED')
> Razvan
>|||You might want to add some other constraints. I would not allow the
low and high values to be the same; disjoint ranges will allow you to
use a more readable BETWEEN predicate.
CREATE TABLE Table1
(foo_code CHAR (10) NOT NULL,
low_val DECIMAL(6,0) NOT NULL,
high_val DECIMAL(6,0) NOT NULL,
use_this CHAR (10) DEFAULT '{{ none }}' NOT NULL,
CHECK (low_val <= high_val)
PRIMARY KEY (foo_code,low_val, high_val),
UNIQUE (foo_code,low_val),
UNIQUE (foo_code, high_val)
);
Besides not having overlaps, you might want to avoid gaps in the
ranges.
CREATE TRIGGER Table1_No_Gaps
ON Table1 FOR INSERT, UPDATE
AS
BEGIN
IF EXISTS
(SELECT *
FROM Table1 AS T1
GROUP BY T1.foo_code
HAVING MAX(high_val)- MIN(low_val) +1
= SUM(high_val - low_val + 1)
BEGIN
RAISERROR ('Code Range Errors',16,1);
ROLLBACK TRANSACTION;
END;
END;sql

Monday, March 26, 2012

how to encrypt db files

Came across the following on best practises as well
" Use the SQL Server service account to encrypt database files with EFS."
How do you set it up ?Just because it is on someone's best practices list, doesn't mean it should
just be grabbed and executed. When you encrypt the files on the OS, you
incur a performance hit everytime they need to be accessed to do the
decrypt/encrypt. Since a database server never quits reading or writing to
the files, this can be a rather heavy load on the machine and cause
significant degradation in performance.
Mike
http://www.solidqualitylearning.com
Disclaimer: This communication is an original work and represents my sole
views on the subject. It does not represent the views of any other person
or entity either by inference or direct reference.
"Hassan" <Hassan@.hotmail.com> wrote in message
news:exfOsOKIGHA.1424@.TK2MSFTNGP12.phx.gbl...
> Came across the following on best practises as well
> " Use the SQL Server service account to encrypt database files with EFS."
> How do you set it up ?
>|||>decrypt/encrypt. Since a database server never quits reading or writing to
Actually SQL2005 seems to close the file if no active query is running...
-- AntiSpam/harvest --
Remove X's to send email to me.|||The server is supposed to hold the individual database files open and in
a ready state regardless of user activity. Are you sure you don't have
the autoclose property turned on for the database you are looking at?
That is:
select databaseproperty('<dbname>', 'IsAutoClose')
*mike hodgson*
http://sqlnerd.blogspot.com
Josh Assing wrote:

>Actually SQL2005 seems to close the file if no active query is running...
>
>-- AntiSpam/harvest --
>Remove X's to send email to me.
>|||Hi Hassan,
Encrypting your data files can be a prudent measure (MSDE instance on a
field salesperson's laptop with customer data, for example). I
wouldn't necessarily recommend it on the server side.
Here is a nice how-to on encrypting your files using EFS...
http://www.sqlservercentral.com/col...menting_efs.asp

How to enable the Transport protocol while communicating between two different servers

Whenever I start my SQL Express 2005 database, I get the following in the logs :

<SNIP>
2005-11-20 19:04:11.92 spid8s Starting up database 'tempdb'.
2005-11-20 19:04:11.99 spid5s Error: 8355, Severity: 16, State: 1.
2005-11-20 19:04:11.99 spid5s Service Broker is disabled in MSDB or MSDB failed to start. Server level event notifications can not be delivered. Event notifications with FAN_IN in other databases could be affected as well.
2005-11-20 19:04:11.99 spid11s The Service Broker protocol transport is disabled or not configured.
2005-11-20 19:04:11.99 spid5s Recovery is complete. This is an informational message only. No user action is required.
2005-11-20 19:04:11.99 spid11s The Database Mirroring protocol transport is disabled or not configured.
2005-11-20 19:04:12.04 spid11s Service Broker manager has started.
</SNIP>

I also get "Service Broker is disabled in MSDB or MSDB failed to start. Server level event notifications can not be delivered. Event notifications with FAN_IN in other databases could be affected as well." in the event logs.

This is on a Windows 2003 SP1 server, and was an upgrade to an existing MSDE 2000 database.

Does anyone have any ideas what causes this, and how to fix it?

If you don't care about Service Broker functionality or any other functionality dependent on it (Event Notifications, Query Notifications, SqlDependency, SQL database mail etc) then you can simply ignore the message.

If you need Service Broker functionality, you should enable back the broker in MSDB:

ALTER DATABASE [msdb] SET ENABLE_BROKER;

HTH,
~ Remus

|||Thanks for the quick reply! Everything seems to be working despite this message, meaning my application can connect to the database and query/update it, so I think I'll just ignore the message for now. If something starts acting up, I'll enable it to see if that helps.
|||If i want to exchange message between two different instances or databases in two different servers, then I have to enable the transport protocol which wil be disabled by default in service broker.I read in some article that some registry settings has to be changed.So can someone suggest on the same.|||When I try to execute this statement, the query just continues to run and run. If I use the GUI, it instantly hangs the task. Any thoughts as to why and how to fix would be great. Thx, Cin|||

You need to stop SQL Agent for this statement to complete.

Wednesday, March 21, 2012

How to Eliminate Nodes with Null values?

I need to shred the xml data to retrieve BrandIDs based on the following business rules.

/**************************************************************************************************************************

(1) Not every instance of xml would contain BrandIDs node

(2) Ignore BrandIDs whenever its a descendant of AlternativeState

(3) We are interested in the data stored under MarketSize whenever the CurrentEvent node is MarketSize.

(4) We are interested in the data stored under OtherEvent whenever the CurrentEvent node is not MarketSize.

****************************************************************************************************************************/

While shredding the xml data, I have noticed that out of 200,000 xml rows there are only 1000 BrandIDs nodes that do actually have data in them (e.g. <BrandIDs> 123, 234</BrandIDs>. Others are just blank in the form of </BrandIDs>. I would like to modify XQuery given below so that I could filter out such rows where even though BrandIDs node exist but it has no scalar value for me to retrieve. From the sample query result given at the end you would notice that the third row is empty. I would like to avoid such rows in result set.

I am open to any suggestions here if anyone out there could come up with a better solution.

declare @.xml xml

set @.xml =

'

<State>

<StatsState>

<CurrentState>

<BrandIDs>2698741</BrandIDs>

</CurrentState>

</StatsState>

</State>

<State>

<StatsState>

<CurrentState>

<OtherEvents>

<BrandIDs>160603,160737</BrandIDs>

</OtherEvents>

<CurrentEvent>BrandShare</CurrentEvent>

</CurrentState>

</StatsState>

</State>

<State>

<StatsState>

<CurrentState>

<MarketSize>

<BrandIDs />

<AlternativeState>

<CurrentEvent>None</CurrentEvent>

<BrandIDs>25630,8956201</BrandIDs>

</AlternativeState>

<CompanyIDs />

</MarketSize>

<CurrentEvent>MarketSize</CurrentEvent>

</CurrentState>

</StatsState>

</State>

<State>

<StatsState>

<CurrentState>

<OtherEvents>

<BrandIDs>2001,2002,2003,2004,2005,2006</BrandIDs>

</OtherEvents>

<CurrentEvent>BrandShare</CurrentEvent>

<MarketSize>

<BrandIDs>40666,71788,201225</BrandIDs>

</MarketSize>

</CurrentState>

</StatsState>

</State>

'

SELECT

Element.Val.query(

'for $s in self::node()

where $s//*/BrandIDs[not(parent::AlternativeState)]

return

if (data(($s/StatsState/CurrentState/CurrentEvent)[1]) = "MarketSize")

then $s/StatsState/CurrentState/MarketSize/BrandIDs/text()

else (

if (data(($s/StatsState/CurrentState/CurrentEvent)[1]) != "MarketSize")

then $s/StatsState/CurrentState/OtherEvents/BrandIDs/text()

else $s//BrandIDs/text())

') AS BrandIDs

FROM @.xml.nodes('/State') AS Element(Val)

GO

BrandIDs

-

2698741

160603,160737

2001,2002,2003,2004,2005,2006

If an element is empty then it does not have any child nodes meaning you can check with e.g. BrandIDs[node()] for BrandIDs elements that are not empty.

So your query could be written as

Code Snippet

SELECT

Element.Val.query(

'for $s in self::node()

return

if (data(($s/StatsState/CurrentState/CurrentEvent)[1]) = "MarketSize")

then $s/StatsState/CurrentState/MarketSize/BrandIDs/text()

else (

if (data(($s/StatsState/CurrentState/CurrentEvent)[1]) != "MarketSize")

then $s/StatsState/CurrentState/OtherEvents/BrandIDs/text()

else $s//BrandIDs/text())

') AS BrandIDs

FROM @.xml.nodes('/State[.//*/BrandIDs[node() and not(parent::AlternativeState)]]') AS Element(Val)

|||

Hi marton,

Thanks once more for helping me out here. Your proposed solution does solve my problem. Is there any way that perhaps you could use the 'where' clause in FLWOR to apply the same condition? I actually have a requirement to use @.xml.nodes('/State'). I do have different set of FLWOR queries to read values for different nodes and for each the root node is always /State and I would need to combine all of them in one statement. So preferably I would like to keep the nodes clause pointing to root.

Hope you get my point.

thanks again

|||The problem is that the nodes methods shreds the xml variable into rows that you then query with the query method. So for the original example you got four rows in the result set as the nodes method yields four rows, independent of the query applied later to the each row. If you want to eliminate nodes to not yield rows at all then I think it as to be done with the nodes method.|||

Hi Martin,

Thanks for clarification. I understand your point.

I actually works with xml where each of the node goes to its own relational table and I wanted to have only one select statement where each xml row is read only once and I get all of the values for nodes by specifying any business rules within FLWOR there. Hence I hesitate to specify any specific node such as BrandIDs in nodes() because it wouldn't leave an option for me to work with other nodes. I think I would have to use function for each node and call them from my select statement.

Many thanks

Wednesday, March 7, 2012

how to do update of select columns based on...

the following criteria.
i have the selection all done but am trying to figure out how to do the following:
if column4 < 0 then add column4 to column3, move 0 to column4;
if column3 < 0 then add column3 to column2, move 0 to column3;
if column2 < 0 then add column2 to column1, move 0 to column2;
add column3 to column4;
move column2 to column3;
move column1 to column2;
if column0 > 0 move column0 to column1, move 0 to column0 else move 0 to column1;

these are all numeric data types.Why are you moving columns? Here's a hint on how to do it. Go look up CASE expressions in your manual.

SELECT CASE WHEN column4 < 0 THEN column4 + column3 ELSE 0 END As 'An Example'
FROM MyTable|||There are many ways to accomplish what you've specified, but the simplest way is for you to code the steps as you've described them... That will be the easiest for you to understand going forward because it is how you think about the operations involved.

If you are looking for one of the other ways to go about this, you'll have to explain what you want in a bit more detail. If this is what you want, I'd describe the problem in terms of the real world instead of in terms of the columns that exist in your database now... There may be a much better way to get the same answer!

-PatP|||i have 5 columns that represent aged balances.
0 thru 4
the first part about with checking the values to 0 is due to some bad data since a - negative balance should not be aged i want to roll it down to column0 in order for the age to be current
then after that is done i want to really age the balances forward 1 column each. the first column 0 will be the new current amount due so if it is negative i want to move 0 to my next column1. if it is not negative then i want to add column0 to column1 and move 0 to column0 so then when i go thru another process i add the new billing amount to the column0 (current due)|||is there a better way? (i am way to un-educated on sql syntax/options)

update ACCTF_TEST
set a_curr = case when a_120 < 0 then a_120 + a_curr else a_curr end,
a_120 = case when a_120 < 0 then 0 else a_120 end
where a_lastage <> 20060402
go
update ACCTF_TEST
set a_curr = case when a_90 < 0 then a_90 + a_curr else a_curr end,
a_90 = case when a_90 < 0 then 0 else a_90 end
where a_lastage <> 20060402
go
update ACCTF_TEST
set a_curr = case when a_60 < 0 then a_60 + a_curr else a_curr end,
a_60 = case when a_60 < 0 then 0 else a_60 end
where a_lastage <> 20060402
go
update ACCTF_TEST
set a_curr = case when a_30 < 0 then a_30 + a_curr else a_curr end,
a_30 = case when a_30 < 0 then 0 else a_30 end
where a_lastage <> 20060402
go
update ACCTF_TEST
set a_120 = a_120 + a_90,
a_90 = 0
where a_lastage <> 20060402
go
update ACCTF_TEST
set a_90 = a_90 + a_60,
a_60 = 0
where a_lastage <> 20060402
go
update ACCTF_TEST
set a_60 = a_60 + a_30,
a_30 = 0
where a_lastage <> 20060402
go
update ACCTF_TEST
set a_30 = case when a_curr > 0 then a_curr else 0 end,
a_curr = case when a_curr > 0 then 0 else a_curr end
where a_lastage <> 20060402|||Relational databases aren't spreadsheets.

Could you explain the BUSINESS purpose of what you're doing as opposed to how you think the technical process should occur? It sounds a lot like you're trying to use MSSQL like it was an excel spreadsheet, that's going to bite you if true.|||1) original files were non-sql (proprietery format - flat files)
original applications COBOL code
2) customers wanted sql file system for our current apps (COBOL-Acucorp)
3) acucorp announces sql compliance via ntwdblib.dll (little/no change required)
4) we implimented said compliance
5) complaints about slowness
6) optimized code to take advantage of where constraint when possible
7) still complaints about slowness
8) create stored proceedures to do some of the actual COBOL programs to bypass the ntwdblib
9) i get assigned this task - reduce time to AGE accounts and to reset the current balance to 0 for the UPDATE process to load it.
10) yes we are in process of writing a non-ntwdblib binding app(strickly sql code)
11) its about 2 yrs out
12) complaints still coming in...|||Bear in mind that I'm not 100% sure of how you want to present the aging, but what I would use to replace all of your code would look something a lot like this:UPDATE ACCTF_TEST
SET a_curr = a_curr
+ CASE WHEN a_30 < 0 THEN a_30 ELSE 0 END
+ CASE WHEN a_60 < 0 THEN a_60 ELSE 0 END
+ CASE WHEN a_90 < 0 THEN a_90 ELSE 0 END
+ CASE WHEN a_120 < 0 THEN a_120 ELSE 0 END
, a_30 = CASE WHEN a_curr < 0 THEN 0 ELSE a_curr END
, a_60 = CASE WHEN a_30 < 0 THEN 0 ELSE a_30 END
, a_90 = CASE WHEN a_60 < 0 THEN 0 ELSE a_60 END
, a_120 = CASE WHEN a_90 < 0 THEN 0 ELSE a_90 END + a_120 -- To acheive "bucket brigade"
WHERE a_lastage <> 20060402-PatP

How to do this...in mdx query?

In a MDX query how to create a new member within the same dimension. The following is my MDX query:

OLAP cube: AP Statistics by Cancer Centre

Dimension: DIM_Fiscal_Year

Attribute: Fiscal Year

Attribute: Fiscal Year Full

WITH MEMBER [Measures].[ParameterCaption] AS '[DIM_Fiscal_Year].[Fiscal Year].CURRENTMEMBER.MEMBER_CAPTION'

MEMBER [Measures].[ParameterValue] AS '[DIM_Fiscal_Year].[Fiscal Year].CURRENTMEMBER.UNIQUENAME'

MEMBER [Measures].[ParameterLevel] AS '[DIM_Fiscal_Year].[Fiscal Year].CURRENTMEMBER.LEVEL.ORDINAL'

MEMBER [Measures].[FY] AS '[DIM_Fiscal_Year].[Fiscal Year Full].CURRENTMEMBER.MEMBER_CAPTION'

SELECT {[Measures].[FY], [Measures].[ParameterCaption], [Measures].[ParameterValue], [Measures].[ParameterLevel]} ON COLUMNS , {ORDER({FILTER([DIM_Fiscal_Year].[Fiscal Year].MEMBERS,[Measures].[ParameterLevel]=1)},([Measures].[ParameterCaption]), DESC)} ON ROWS FROM [AP Statistics by Cancer Centre]

New member is in Red, It returns the value "All" for the entire "FY" column.

2008 All 2008 [DIM_Fiscal_Year].[Fiscal Year].&[2008] 1

2007 All 2007 [DIM_Fiscal_Year].[Fiscal Year].&[2007] 1

2006 All 2006 [DIM_Fiscal_Year].[Fiscal Year].&[2006] 1

Thanks

Could you explain the structure of [DIM_Fiscal_Year] with examples - and is any relationship defined between the [Fiscal Year] and [Fiscal Year Full] attributes? From the results above, it looks like [Fiscal Year Full] is not related to [Fiscal Year].

|||

The reason I have the "fiscal_year" and "fiscal_year_full" is because 'fiscal_year" is a 4 digit year of the fiscal year and was used to create the "Time" Dimension and fiscal_year_full is the full description of the fiscal year. The following is an example:

fiscal year.........2007

fiscal year full....2006-07

I use the fiscal year full to display in the report.

|||

In that case, if you relate "fiscal year full" to "fiscal year" via an attribute relationship (while removing "fiscal year full" from its existing attribute relationship), then the appropriate "fiscal year full" member should be selected when you select a "fiscal year" member. One way to do this would be to drag "fiscal year full" under "fiscal year", as described below:

SQL Server 2005 Books Online

Defining and Configuring an Attribute Relationship

...

You can create an attribute relationship between any two attributes in a dimension. With the Attributes pane of Dimension Designer set to tree view, drag the attribute that you want to relate to another attribute onto the <new attribute relationship> field under the attribute.

...

How to do this in a report?

I have to write a report in SQL that takes the following data structure:
CREATE TABLE [dbo].[Sales_Customer_List] (
[cust_no] [char] (10) NOT NULL ,
[cust_name] [char] (35) NULL ,
[distr_channel] [char] (2) NOT NULL ,
[sold_to_sales_grp] [char] (3) NULL ,
[ship_to_sales_grp] [char] (3) NULL ,
[sold_to_sales_rep_cd] [char] (10) NULL ,
[ship_to_sales_rep_cd] [char] (10) NULL ,
[sold_to_sales_rep] [varchar] (30) NULL ,
[ship_to_sales_rep] [varchar] (30) NULL ,
[csr] [char] (35) NOT NULL ,
[csr_email] [char] (60) NOT NULL ,
[credit_mgr] [char] (35) NOT NULL ,
[sales_region] [char] (20) NULL ,
[BusArea01] [decimal](18, 2) NULL ,
[BusArea02] [decimal](18, 2) NULL ,
[BusArea03] [decimal](18, 2) NULL
) ON [PRIMARY]
--GO
and gives me a listing by customer number, customer name,
sold_to_sales_grp, etc thru the Sales region field.
The data itself can have multiple distr_channel values but the other
fields (excluding the busarea01, 02 and 03 fields) will not change
between customers.
The data would be like:
custno = 1234
custname= Customer1
distr_channel = DS
etc etc etc and the BusArea fields would be
BusArea01 = 0
BusArea02 = 137
BusArea03 = 984
A second record would be:
custno = 1234
custname= Customer1
distr_channel = GM
etc etc etc and the BusArea fields would be
BusArea01 = 855
BusArea02 = 0
BusArea03 = 211
A Third record would be:
custno = 6543
Custname = Customer2
distr_channel = CH
etc etc etc and the BusArea fields would be
BusArea01 = 1250
BusArea02 = 0
BusArea03 = 335
A fourth record would be
Custno = 8998
Custname = Customer3
distr_channel = DL
etc etc etc and the BusArea fields would be
BusArea01 = 25000
BusArea02 = 0
BusArea03 = 550
A fifth record would be
Custno = 8998
Custname = Customer3
distr_channel = WA
etc etc etc and the BusArea fields would be
BusArea01 = 0
BusArea02 = 15000
BusArea03 = 0
The line I need to have on my report would be:
C No C Name BA01 BA02 BA03
1234 Customer1 etc etc etc GM 855 DS 137 DS & GM 211 + 984
6543 Customer2 etc etc etc CH 1250 CH 0 CH 335
8998 Customer3 etc etc etc DL 25000 WA 15000 DL 550
Some customers would have 1 Distr_channel, some 4 or 5.
How would you do this in SQL?
Thanks,
SCBetter if you do this in the client app / reporting tool and not in sql serv
er.
HOW TO: Rotate a Table in SQL Server
http://support.microsoft.com/defaul...574&Product=sql
Dynamic Crosstab Queries
http://www.windowsitpro.com/SQLServ...5608/15608.html
Dynamic Cross-Tabs/Pivot Tables
http://www.sqlteam.com/item.asp?ItemID=2955
AMB
"Blasting Cap" wrote:

> I have to write a report in SQL that takes the following data structure:
> CREATE TABLE [dbo].[Sales_Customer_List] (
> [cust_no] [char] (10) NOT NULL ,
> [cust_name] [char] (35) NULL ,
> [distr_channel] [char] (2) NOT NULL ,
> [sold_to_sales_grp] [char] (3) NULL ,
> [ship_to_sales_grp] [char] (3) NULL ,
> [sold_to_sales_rep_cd] [char] (10) NULL ,
> [ship_to_sales_rep_cd] [char] (10) NULL ,
> [sold_to_sales_rep] [varchar] (30) NULL ,
> [ship_to_sales_rep] [varchar] (30) NULL ,
> [csr] [char] (35) NOT NULL ,
> [csr_email] [char] (60) NOT NULL ,
> [credit_mgr] [char] (35) NOT NULL ,
> [sales_region] [char] (20) NULL ,
> [BusArea01] [decimal](18, 2) NULL ,
> [BusArea02] [decimal](18, 2) NULL ,
> [BusArea03] [decimal](18, 2) NULL
> ) ON [PRIMARY]
> --GO
> and gives me a listing by customer number, customer name,
> sold_to_sales_grp, etc thru the Sales region field.
> The data itself can have multiple distr_channel values but the other
> fields (excluding the busarea01, 02 and 03 fields) will not change
> between customers.
> The data would be like:
> custno = 1234
> custname= Customer1
> distr_channel = DS
> etc etc etc and the BusArea fields would be
> BusArea01 = 0
> BusArea02 = 137
> BusArea03 = 984
> A second record would be:
> custno = 1234
> custname= Customer1
> distr_channel = GM
> etc etc etc and the BusArea fields would be
> BusArea01 = 855
> BusArea02 = 0
> BusArea03 = 211
> A Third record would be:
> custno = 6543
> Custname = Customer2
> distr_channel = CH
> etc etc etc and the BusArea fields would be
> BusArea01 = 1250
> BusArea02 = 0
> BusArea03 = 335
> A fourth record would be
> Custno = 8998
> Custname = Customer3
> distr_channel = DL
> etc etc etc and the BusArea fields would be
> BusArea01 = 25000
> BusArea02 = 0
> BusArea03 = 550
> A fifth record would be
> Custno = 8998
> Custname = Customer3
> distr_channel = WA
> etc etc etc and the BusArea fields would be
> BusArea01 = 0
> BusArea02 = 15000
> BusArea03 = 0
>
> The line I need to have on my report would be:
> C No C Name BA01 BA02 BA03
> 1234 Customer1 etc etc etc GM 855 DS 137 DS & GM 211 + 984
> 6543 Customer2 etc etc etc CH 1250 CH 0 CH 335
> 8998 Customer3 etc etc etc DL 25000 WA 15000 DL 550
> Some customers would have 1 Distr_channel, some 4 or 5.
> How would you do this in SQL?
>
> Thanks,
> SC
>

Friday, February 24, 2012

How to do this conditional(maybe?) query

I'm trying to figure out how do a particular query.

Given that I know how to get the following results from a query (details below):

client1, MT
client2, WA
client3, MT
client3, WA
client3, ID
...

How do I fashion a query that, when a client is listed in more than one state (like client3), the query will only return a single record (instead of three) but print 'MULTIPLE' instead of listing the specific states.

<details>
Here's the set up. I have a table of clients (tblClients), a table of US states (tblStates) and 'linking' table (tblClientState) to id which states a particular client operates in. The reason for the linking table is that a client can operate in one or many different states.

The tables look like this:

tblClients:
client_id, client_name

tblStates:
state_abbrv, state_name

tblClientState:
client_id, state_abbrv

An example query I'm working with is to return a list with the client_name and the state_abbrv.

SELECT client_name, state
FROM tblClients JOIN tblClientState ON tblClients.client_id = tblClientState.client_id

This would return a result like this:

client1, MT
client2, WA
client3, MT
client3, WA
client3, ID
...

Again, here's my question:

How do I fashion a query that, when a client is in more than one state (like client3), the query will only return a single record (instead of three) but have it say 'MULTIPLE' instead of listing the specific states.

It seems like I might be able to use some conditions in my SELECT statement but I can't figure out how to make it all happen.
</details>

Thanks!

Eric LundTry using CASE:

SELECT client_name,
CASE WHEN COUNT(*) = 1 THEN MAX(state) ELSE 'MULTIPLE' END
FROM ...
GROUP BY client_name;|||Wow! Perfect!

That's just the kind of simple, sweet answer I was hoping I would get out of this group!

I was able to take your suggestion and build on it a little bit (because of course, my example was a little over simplified) and I got just EXACTLY what I was looking for.

Thanks a LOT. I really appreciate it!

Eric

How to do the following sql query

How to do the following using sql statements?
I would like to be able to have the following table
Everytime I insert a new record the AutoIncrementKey field will increase by one
but I want the PriKey to be in the order of the datetime as shown below.
INSERT TABLE DateTime = '1/1/2001 12:00:00'
INSERT TABLE DateTime = '31/1/2001 8:00:00'
INSERT TABLE DateTime = '18/1/2001 4:00:00'
INSERT TABLE DateTime = '21/1/2001 3:00:00'
.........
.........
DateTime AutoIncrementKey PriKey(according to date)
1/1/2001 12:00:00 1 1
31/1/2001 8:00:00 2 4
18/1/2001 4:00:00 3 2
21/1/2001 3:00:00 4 3

How to do this?"Steve" <ngsteve@.my-deja.com> wrote in message
news:976e0586.0309040836.3ccd556a@.posting.google.c om...
> How to do the following using sql statements?
> I would like to be able to have the following table
> Everytime I insert a new record the AutoIncrementKey field will increase
by one
> but I want the PriKey to be in the order of the datetime as shown below.
> INSERT TABLE DateTime = '1/1/2001 12:00:00'
> INSERT TABLE DateTime = '31/1/2001 8:00:00'
> INSERT TABLE DateTime = '18/1/2001 4:00:00'
> INSERT TABLE DateTime = '21/1/2001 3:00:00'
> .........
> ........
> DateTime AutoIncrementKey PriKey(according to date)
> 1/1/2001 12:00:00 1 1
> 31/1/2001 8:00:00 2 4
> 18/1/2001 4:00:00 3 2
> 21/1/2001 3:00:00 4 3
> How to do this?

Only with extreme difficulty because inserting a row may change the PriKey
of every other row.

EG
after
INSERT TABLE DateTime = '1/1/2001 12:00:00'
INSERT TABLE DateTime = '31/1/2001 8:00:00'

you have

DateTime AutoIncrementKey PriKey(according to date)
1/1/2001 12:00:00 1 1
31/1/2001 8:00:00 2 2

then, after

after
> INSERT TABLE DateTime = '18/1/2001 4:00:00'

you have

DateTime AutoIncrementKey PriKey(according to date)
1/1/2001 12:00:00 1 1
31/1/2001 8:00:00 2 3
18/1/2001 4:00:00 3 2

Very, very ugly stuff.

Do do this you would have to run something like

update my_table t set prikey = (select 1+count(*) from my_table where
my_date < t.my_date)

in an update, insert and delete trigger.

Very ugly stuff, and very slow and 100% guaranteed to scale poorly.

David|||> Everytime I insert a new record the AutoIncrementKey field will increase
by one
> but I want the PriKey to be in the order of the datetime as shown below.

Why do you need to STORE this data? I would write a stored procedure or
view that calculated it at select time. As David points out, you would need
triggers to do this and it would certainly kill the performance of your app.

(Also, not sure why this was posted to comp.databases.paradox?)

A|||Aaron Bertrand - MVP wrote:
> (Also, not sure why this was posted to comp.databases.paradox?)
Maybe because it's a paradox database and the queston should not have been
crossposted to the sql server groups ...|||First of all, the request for additional columns this table is redundant.
There is no information about the nature of the datetime column; is it
unique? If so, declare it as your primary key, there is no need for another
column.

CREATE TABLE tbl (
dt DATETIME NOT NULL PRIMARY KEY ) ;

If you need a numeric identifier, the prikey column will suffice & the
'autoincrementkey' makes little sense. What is the rule for serialization in
case of multi-row inserts? How do you even know the order in which row is
inserted ? A popular workaround used in t-SQL is to use an IDENTITY column
like:

CREATE TABLE tbl (
dt DATETIME NOT NULL PRIMARY KEY,
autoincr INT NOT NULL IDENTITY);

And you can have a view like:

CREATE VIEW (dt, col, incr)
AS
SELECT dt, ( SELECT COUNT(*)
FROM tbl t1
WHERE t1.dt <= tbl.dt) AS "intcol",
autoincr
FROM tbl ;

--
- Anith
( Please reply to newsgroups only )|||> > (Also, not sure why this was posted to comp.databases.paradox?)
> Maybe because it's a paradox database and the queston should not have been
> crossposted to the sql server groups ...

Well, I figured majority rules. :-)|||DateTime Mode
1/1/2001 12:00:00 1
31/1/2001 8:00:00 7
18/1/2001 4:00:00 3
21/1/2001 3:00:00 3
21/1/2001 5:00:00 3
22/1/2001 3:00:00 7
22/1/2001 8:00:00 7
23/1/2001 3:00:00 3
23/1/2001 9:00:00 5

What I actually want to do is just this, the insertion might not be in
any order or time,
for the above table,
get the total time for each mode Example
Mode 1 Duration = 31/1/2001 8:00:00 - 1/1/2001 12:00:00
Mode 7 Duration= 18/1/2001 4:00:00 - 31/1/2001 8:00:00 + 23/1/2001
3:00:00 - 22/1/2001 3:00:00
Mode 3 Duration= 22/1/2001 3:00:00 - 18/1/2001 4:00:00 + 23/1/2001
9:00:00 - 23/1/2001 3:00:00
Mode 5 Duration= CurrentTime Now - 23/1/2001 9:00:00
How should the sql statement be?
I actually wanted to get the starttime using the statement below but
how to get the endtimes?
Select DateTime, AutoIncrementKey Where Mode = 1
Select DateTime, AutoIncrementKey Where Mode = 7
Select DateTime, AutoIncrementKey Where Mode = 3
Select DateTime, AutoIncrementKey Where Mode = 5|||Steve,

I think you are not following the implications. The calculation you have
shown as :

>>
Mode 1 Duration =
31/1/2001 8:00:00 - 1/1/2001 12:00:00
Mode 7 Duration =
18/1/2001 4:00:00 - 31/1/2001 8:00:00 +
23/1/2001 3:00:00 - 22/1/2001 3:00:00
Mode 3 Duration =
22/1/2001 3:00:00 - 18/1/2001 4:00:00 +
23/1/2001 9:00:00 - 23/1/2001 3:00:00
Mode 5 Duration =
CurrentTime Now - 23/1/2001 9:00:00 <<

depends on the how the rows are being represented positionally in the table.
In other words, for you to decide which datetime value to be subtracted from
which other one, you have to rely on the position of a row in relative to
another. This cannot be, since the rows in a table are not ordered, it may
return different ordering of rows under various circumstances. You have 3
rows with mode 7 and 4 rows with mode 3. How do you decide which one should
be considered for Mode 7 & Mode 3 calculations in which order?

To do this reliably, you need to have a logical value ( loosely put, another
column which can represent the required sequence of datetime values on which
you do your calculations ) for each datetime value.

--
- Anith
( Please reply to newsgroups only )

How to do Minof max and maxof min Calculation in SQL


Hi all,
I have two tables say A and B. and i have the following fields in the two tables
A B
vc_low(say 32) min_vc(say 35)
What is the query to get the MAX of these two fields
It should be like max(vc_low,min_vc),....But i dont know how to form a querry in SQL..
Can any one help me .........

Thanks in AdvanceYou can use CASE clause. From your subject and message i've drafted below example:
create table test1 (id1 int)
insert into test1 values(1)
insert into test1 values(2)
create table test2 (id2 int)
insert into test2 values(11)
insert into test2 values(12)
select 'max value' = case when min(test1.id1) > min(test2.id2) then min(test1.id1) when min(test2.id2) > min(test1.id1) then min(test2.id2) END from test1,test2
The result of the above query will 11
hope the above helps you.
-srikanthr

Sunday, February 19, 2012

how to do grouping

how to get report like this, I am using RS2005
From Query I am getting following data
Name,Catageory,ItemcODE,ItemQty
A CAT1 1 1
A CAT1 2 20
A CAT1 3 15
A CAT1 4 2
A CAT1 5 11
B CAT2 1 18
B CAT2 2 20
B CAT2 3 22
C CAT3 1 0
C CAT3 2 32
For above dataset I want to have report like this
Name : A
Catagoery : CAT1
Item Qty
1 1
2 20
and so on
Name : B
Catagoery : CAT2
Item Qty
1 18
2 20
and so on
Name : C
Catagoery : CAT3
Item Qty
1 0
2 32
and so on
i am new to reporting server 2005,
On table, I inserted a Group on Categoery
and again another group on Items
i am getting only one row for each Item,
where i am doing mistake or Is there anyway to todo,
thanks
kaOn Nov 30, 3:06 pm, Kalyan <Kal...@.discussions.microsoft.com> wrote:
> how to get report like this, I am using RS2005
> From Query I am getting following data
> Name,Catageory,ItemcODE,ItemQty
> A CAT1 1 1
> A CAT1 2 20
> A CAT1 3 15
> A CAT1 4 2
> A CAT1 5 11
> B CAT2 1 18
> B CAT2 2 20
> B CAT2 3 22
> C CAT3 1 0
> C CAT3 2 32
> For above dataset I want to have report like this
> Name : A
> Catagoery : CAT1
> Item Qty
> 1 1
> 2 20
> and so on
> Name : B
> Catagoery : CAT2
> Item Qty
> 1 18
> 2 20
> and so on
> Name : C
> Catagoery : CAT3
> Item Qty
> 1 0
> 2 32
> and so on
> i am new to reporting server 2005,
> On table, I inserted a Group on Categoery
> and again another group on Items
> i am getting only one row for each Item,
> where i am doing mistake or Is there anyway to todo,
> thanks
> ka
You will want to create a group on Name and then another one on
Category (via: right-clicking the top-left corner of the table control
>> select Properties >> select the Groups tab >> select the 'Add...'
button >> Enter a Name and below 'Group on: Expression' select: Fields!
Name.Value >> then select 'Include group header'). Then for the group
on Category, do the same thing except set the 'Group on: Expression'
to Fields!Category.Value. Then below 'Parent group' select the
expression: Fields!Name.Value. You might need to put the same
expressions in the new group rows that have been added in the table
control. Hope this helps.
Regards,
Enrique Martinez
Sr. Software Consultant