Showing posts with label column. Show all posts
Showing posts with label column. Show all posts

Tuesday, March 27, 2012

aliasing two columns in SQL

Hi,

Here is my original query:

select rosterid, lastname, firstname from table
order by lastname

I would like to use column aliasing to display
lastname, firstname in a column entitled name.

I tried the following syntax, but it's not working:

select rosterid, lastname+', '+firstname as name
from table
order by name

This results in a 2 column table with the headings "ROSTERID" and
"NAME". However, NAME contains th last name only, rather than "lastname,
firstname".

Any help greatly appreciated.

Thanks,
Google Jeny

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!One thing worth looking at is not using reserved words such as Name.
You need to change this to something different.

R

Google Jenny <michiamo@.yahoo.com> wrote in message news:<412cfc29$0$14430$c397aba@.news.newsgroups.ws>...
> Hi,
> Here is my original query:
> select rosterid, lastname, firstname from table
> order by lastname
>
> I would like to use column aliasing to display
> lastname, firstname in a column entitled name.
> I tried the following syntax, but it's not working:
> select rosterid, lastname+', '+firstname as name
> from table
> order by name
> This results in a 2 column table with the headings "ROSTERID" and
> "NAME". However, NAME contains th last name only, rather than "lastname,
> firstname".
> Any help greatly appreciated.
> Thanks,
> Google Jeny
>
> *** Sent via Developersdex http://www.developersdex.com ***
> Don't just participate in USENET...get rewarded for it!|||Google Jenny <michiamo@.yahoo.com> wrote in message news:<412cfc29$0$14430$c397aba@.news.newsgroups.ws>...
> Hi,
> Here is my original query:
> select rosterid, lastname, firstname from table
> order by lastname
>
> I would like to use column aliasing to display
> lastname, firstname in a column entitled name.
> I tried the following syntax, but it's not working:
> select rosterid, lastname+', '+firstname as name
> from table
> order by name
> This results in a 2 column table with the headings "ROSTERID" and
> "NAME". However, NAME contains th last name only, rather than "lastname,
> firstname".
> Any help greatly appreciated.
> Thanks,
> Google Jeny
>
> *** Sent via Developersdex http://www.developersdex.com ***
> Don't just participate in USENET...get rewarded for it!

This query works for me in pubs:

select au_id, au_lname + ', ' + au_fname as 'name'
from authors
order by 'name'

Perhaps you could post your CREATE TABLE statement and some sample data?

Simon|||You may want to add the following as well to remove any additional
spaces in the name fields:

select rosterid, rtrim(lastname) +', ' + rtrim(firstname) as Name
from table|||Thanks so much. The rtrim did the trick.

Google Jenny

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!

Aliasing columns for a DMX subquery

I require the column of a nested table (KOL s) as part of the output of my DMX query, which needs to be written out to a relational table. Hence, I flatten the <select_list> of the SELECT DMX query as below:

SELECT FLATTENED

([Speciality].[SPECIALITY ID]) as [Speciality_Id],

(0) as [Bool_NameInAuthors],

(0) as [Bool_EmailInAbstract],

(0) as [Bool_AffiliationInAbstract],

(SELECT ([KOL ID]) as [Id], ([FIRST NAME]) as [FirstName], ([MIDDLE NAME]) as [MiddleName], ([LAST NAME]) as [LastName], ([AFFILIATION]) as [Affiliation], ([EMAILADDRESS]) as [EmailAddress] FROM [Speciality].[KO Ls]),

(SELECT ([Speciality Term DESCRIPTION]) as [Term] FROM [Speciality].[SPECIALITYTERMS]) AS Spec

From

[Speciality]

PREDICTION JOIN

OPENQUERY([ETL Profiler DB],

'SELECT

[SPECIALITY_ID]

FROM

[dbo].[KOLs]

') AS t

ON

[Speciality].[SPECIALITY ID] = t.[SPECIALITY_ID]

However, this causes the subquery columns (ID, FirstName, ...) to be aliased as Expression.ID, Expression.FirstName...

How do I alias these flattened columns properly?

I tried to alias the subquery to a derived table (as follows), but it just replaces the Expression word by the derived table alias (KOL in this case). So, does not solve my problem.

(SELECT ([KOL ID]) as [Id], ([FIRST NAME]) as [FirstName], ([MIDDLE NAME]) as [MiddleName], ([LAST NAME]) as [LastName], ([AFFILIATION]) as [Affiliation], ([EMAILADDRESS]) as [EmailAddress] FROM [Speciality].[KO Ls]) AS KOL

You can enclose the entire query in another SELECT where you alias the nested table columns -

SELECT [KOL.Id] as KOL_Id, [KOL.FirstName] as KOL_FirstName, ....

FROM

(SELECT FLATTENED ....) AS TT

sql

Aliasing a column name

Hi,
I'm trying to write a SQL event (view or storied proceedure). I have a table that is meant for reporting....the data is arranged verticle. I deal in Fiscal Years ie 2006/2007, 2007/2008, ect. The table in question has generic column lables ie FY1, FY2. I'm writing a report off the table and I want to dynamically turn FY1 into the current FiscalYear, FY2 into current FiscalYear + 1. I tried:

SELECT dbo.tblBudgetConfig.CurrentBudgetYear, dbo.tblBudgetProjectedCurrent.FY4 AS Left ([dbo.tblbudgetConfig.CurrentBudgetYear],4)+3 & "/" & Right([dbo.tblbudgetConfig.CurrentBudgetYear],4)+3
FROM dbo.tblBudgetConfig INNER JOIN
dbo.tblBudgetProjectedCurrent ON dbo.tblBudgetConfig.CurrentBudgetYear = dbo.tblBudgetProjectedCurrent.CurrentBudgetYear

But SQL squawks everytime I try this and tells me that there is something a miss near 'Left'.

Any help will be appreciated.

Nope, you cannot dynamically alias columns. Columns are part of the definition of the query and have to be there at the end of compile phase, not execution. To do this you would need to use dynamic SQL like EXEC ('query string'). You would have to build up the AS in a prior query .

A couple of things to note:

& does not work in SQL. You have to use + for concatenation (and you have to cast everything to the proper datatype_

"value" does not mean a literal, it means a column name. Use single quotes 'value'

Consider using the user interface to manage such things. This wouldn't be likely possible query anyhow because the data could change row by row, so you could then have a variable column name (it may not in your case, but SQL doesn't know that.) Instead of using the column names, add a column named fiscal year and store your value in there. Then let the UI put it in the right places and make it look all pretty for the user.

|||

AFAIK, you can′t compose the Aliases on the fly.

HTH, Jens K. Suessmeyer.


http://www.sqlserver2005.de

|||Thanks for your help. Its not the answer I was hoping for but what you are saying does make sense. And thanks for the t-sql tips too. I am really new at this so any help is appreciated.

Aliasing a column name

Hi,
I'm trying to write a SQL event (view or storied proceedure). I have a table that is meant for reporting....the data is arranged verticle. I deal in Fiscal Years ie 2006/2007, 2007/2008, ect. The table in question has generic column lables ie FY1, FY2. I'm writing a report off the table and I want to dynamically turn FY1 into the current FiscalYear, FY2 into current FiscalYear + 1. I tried:

SELECT dbo.tblBudgetConfig.CurrentBudgetYear, dbo.tblBudgetProjectedCurrent.FY4 AS Left ([dbo.tblbudgetConfig.CurrentBudgetYear],4)+3 & "/" & Right([dbo.tblbudgetConfig.CurrentBudgetYear],4)+3
FROM dbo.tblBudgetConfig INNER JOIN
dbo.tblBudgetProjectedCurrent ON dbo.tblBudgetConfig.CurrentBudgetYear = dbo.tblBudgetProjectedCurrent.CurrentBudgetYear

But SQL squawks everytime I try this and tells me that there is something a miss near 'Left'.

Any help will be appreciated.

Nope, you cannot dynamically alias columns. Columns are part of the definition of the query and have to be there at the end of compile phase, not execution. To do this you would need to use dynamic SQL like EXEC ('query string'). You would have to build up the AS in a prior query .

A couple of things to note:

& does not work in SQL. You have to use + for concatenation (and you have to cast everything to the proper datatype_

"value" does not mean a literal, it means a column name. Use single quotes 'value'

Consider using the user interface to manage such things. This wouldn't be likely possible query anyhow because the data could change row by row, so you could then have a variable column name (it may not in your case, but SQL doesn't know that.) Instead of using the column names, add a column named fiscal year and store your value in there. Then let the UI put it in the right places and make it look all pretty for the user.

|||

AFAIK, you can′t compose the Aliases on the fly.

HTH, Jens K. Suessmeyer.


http://www.sqlserver2005.de

|||Thanks for your help. Its not the answer I was hoping for but what you are saying does make sense. And thanks for the t-sql tips too. I am really new at this so any help is appreciated.

Aliased column in stored procedure not seen by datagrid

i have an aliased column in an sql statement that works fine when
displaying its output in a datagrid, but when I transfer the sql
statement into a stored procedure , the datagrid can't see it. I get an
error "{"DataBinder.Eval: 'System.Data.DataRowView' does not contain a
property with the name myaliasedcolumn." }Hi

You may want to post the DDL for this. If you are using exactly the same SQL
Statement then it should be the same. You may want make sure that you SET
NOCOUNT ON at the start of the procedure.

John

".Net Sports" <ballz2wall@.cox.net> wrote in message
news:1126914453.889098.79790@.g47g2000cwa.googlegro ups.com...
>i have an aliased column in an sql statement that works fine when
> displaying its output in a datagrid, but when I transfer the sql
> statement into a stored procedure , the datagrid can't see it. I get an
> error "{"DataBinder.Eval: 'System.Data.DataRowView' does not contain a
> property with the name myaliasedcolumn." }

Aliased Column and Where Clauses

I want to use an aliased field with a where caluse as below

select member_ID,
CASE
WHEN (status_id & (16 | 128)) = (16 | 128) OR (status_id & 16 ) = 0
THEN CAST(1 AS bit) ELSE CAST(0 AS bit)
END AS IsMigrated
FROM member
LEFT OUTER JOIN language ON language.language_id = member.country_id
WHERE language = 'Deutsch'
-- AND IsMigrated = 1

However i keep getting "Invalid column name 'IsMigrated'" when i uncomment the AND IsMigrated = 1 line.

That construct is not available in TSQL; you will need to either need to convert that into a function or "spell it out fully" in the where clause.

Here are a few past threads that had related discussions:

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

|||

You could try using a derived table, see below.

Chris

Code Snippet

SELECT t.member_ID,

t.IsMigrated

FROM (

SELECT member_ID,

CASE WHEN (status_id & (16 | 128)) = (16 | 128)

OR (status_id & 16) = 0 THEN CAST(1 AS BIT)

ELSE CAST(0 AS BIT)

END AS IsMigrated

FROM member

LEFT OUTER JOIN language ON language.language_id = member.country_id

WHERE language = 'Deutsch'

) t

WHERE t.IsMigrated = 1

|||

The data behind an 'aliased' column is not known by that alias during the data retreival. You cannot use an 'aliased' column name in the SELECT, JOIN conditions, or WHERE criteria of a query.

However, since the data from the query is 'pulled' into a derived table and then sorted, the derived table will know the 'aliased' data by the column name aliases, and you can use the alias in the ORDER BY

|||

I just keep running into this one...

A question to the developement team of SQL: is there any reason why this hasn't been implemented?

The simplest implementation would be to sunbstitue any reference to a derived column with it's definition, by doing a search & replace on the code before feeding it to the interpreter. I can't figure out why it would be difficult to implement or how it would break existing code.

Simple thing like

Col1+Col2 as Sub1,

col3 + col4 as Sub2,

Sub1 + Sub2 as Total

Shouldn't be too hard for the interpreter to figure out? (Access can do it...)

Also something like

select Col1 + '.' + Col2 as Concat,

... bla bla

Group by Concat

Order by Concat

This would really help to keep your 'eye on the ball' instead of on the technical implementation. It would also help maintainability.

So..... next CTP of Katmai it is then? ;-)

Regards,

Gert-Jan

|||

Post your suggestions at:

Suggestions for SQL Server

http://connect.microsoft.com/sqlserver

Aliased Column and Where Clauses

I want to use an aliased field with a where caluse as below

select member_ID,
CASE
WHEN (status_id & (16 | 128)) = (16 | 128) OR (status_id & 16 ) = 0
THEN CAST(1 AS bit) ELSE CAST(0 AS bit)
END AS IsMigrated
FROM member
LEFT OUTER JOIN language ON language.language_id = member.country_id
WHERE language = 'Deutsch'
-- AND IsMigrated = 1

However i keep getting "Invalid column name 'IsMigrated'" when i uncomment the AND IsMigrated = 1 line.

That construct is not available in TSQL; you will need to either need to convert that into a function or "spell it out fully" in the where clause.

Here are a few past threads that had related discussions:

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

|||

You could try using a derived table, see below.

Chris

Code Snippet

SELECT t.member_ID,

t.IsMigrated

FROM (

SELECT member_ID,

CASE WHEN (status_id & (16 | 128)) = (16 | 128)

OR (status_id & 16) = 0 THEN CAST(1 AS BIT)

ELSE CAST(0 AS BIT)

END AS IsMigrated

FROM member

LEFT OUTER JOIN language ON language.language_id = member.country_id

WHERE language = 'Deutsch'

) t

WHERE t.IsMigrated = 1

|||

The data behind an 'aliased' column is not known by that alias during the data retreival. You cannot use an 'aliased' column name in the SELECT, JOIN conditions, or WHERE criteria of a query.

However, since the data from the query is 'pulled' into a derived table and then sorted, the derived table will know the 'aliased' data by the column name aliases, and you can use the alias in the ORDER BY

|||

I just keep running into this one...

A question to the developement team of SQL: is there any reason why this hasn't been implemented?

The simplest implementation would be to sunbstitue any reference to a derived column with it's definition, by doing a search & replace on the code before feeding it to the interpreter. I can't figure out why it would be difficult to implement or how it would break existing code.

Simple thing like

Col1+Col2 as Sub1,

col3 + col4 as Sub2,

Sub1 + Sub2 as Total

Shouldn't be too hard for the interpreter to figure out? (Access can do it...)

Also something like

select Col1 + '.' + Col2 as Concat,

... bla bla

Group by Concat

Order by Concat

This would really help to keep your 'eye on the ball' instead of on the technical implementation. It would also help maintainability.

So..... next CTP of Katmai it is then? ;-)

Regards,

Gert-Jan

|||

Post your suggestions at:

Suggestions for SQL Server

http://connect.microsoft.com/sqlserver

Alias a column that has 3 values into 3 columns

I want to alias a column that has 3 values into 3 columns, one for each
value. As an example, let’s say Pet_type.CategoryID contains three possib
le
values: Cat, Dog and Hamster. The following SQL works with MySQL. What is
the correct SQL Server syntax for this? I looked in the Transact SQL Guide
but came up empty.
Thank you.
Alan Slutsky
SELECT DISTINCT c1.Name AS Dog, c2.Name AS Cat, c3.Name AS Hamster,
d.title, d.identifier
FROM Canonical c1
LEFT JOIN Entity e1 USING (CanonicalID)
LEFT JOIN Document d USING(DocumentID)
LEFT JOIN Entity e2 USING (DocumentID)
LEFT JOIN Canonical c2 USING (CanonicalID)
LEFT JOIN Canonical c3 USING (CanonicalID)
WHERE c1.CategoryID=”Dog” AND c2.CategoryID=”Cat” and c3.CategoryID=
”Hamster”"aslutsky" <aslutsky@.discussions.microsoft.com> wrote in message
news:BE0AEB86-B15F-4E95-A13B-FBD7FFD748B4@.microsoft.com...
>I want to alias a column that has 3 values into 3 columns, one for each
> value. As an example, let's say Pet_type.CategoryID contains three
> possible
> values: Cat, Dog and Hamster. The following SQL works with MySQL. What
> is
> the correct SQL Server syntax for this? I looked in the Transact SQL
> Guide
> but came up empty.
> Thank you.
> Alan Slutsky
> SELECT DISTINCT c1.Name AS Dog, c2.Name AS Cat, c3.Name AS Hamster,
> d.title, d.identifier
> FROM Canonical c1
> LEFT JOIN Entity e1 USING (CanonicalID)
> LEFT JOIN Document d USING(DocumentID)
> LEFT JOIN Entity e2 USING (DocumentID)
> LEFT JOIN Canonical c2 USING (CanonicalID)
> LEFT JOIN Canonical c3 USING (CanonicalID)
> WHERE c1.CategoryID="Dog" AND c2.CategoryID="Cat" and c3.CategoryID="Hamst
er"
>
Here's my best guess. Notice that I've removed the references to C2 and C3
from the WHERE clause, otherwise the outer join effectively becomes and
inner one - at least it does in standard SQL but I can't verify that for
MySQL.
SELECT DISTINCT c1.name AS dog, c2.name AS cat, c3.name AS hamster,
d.title, d.identifier
FROM Canonical c1
LEFT JOIN Entity e1
ON c1.canonicalid = e1.canonicalid
LEFT JOIN Document d
ON c1.canonicalid = d.canonicalid
LEFT JOIN Entity e2
ON c1.canonicalid = e2.canonicalid
LEFT JOIN Canonical c2
ON c1.canonicalid = c2.canonicalid
AND c2.CategoryID='Cat'
LEFT JOIN Canonical c3
ON c1.canonicalid = c3.canonicalid
AND c3.CategoryID='Hamster'
WHERE c1.CategoryID='Dog' ;
David Portas, SQL Server MVP
Whenever possible please post enough code to reproduce your problem.
Including CREATE TABLE and INSERT statements usually helps.
State what version of SQL Server you are using and specify the content
of any error messages.
SQL Server Books Online:
http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
--|||>> I want to alias a column that has 3 values into 3 columns, one for each v
alue. <<
That makes ABSOLUTELY NO SENSE in RDBMS. A column has a single value
by definition?
No such thing can exist! Do you really only have one PetType as
implied by the singlular name? What kidn of crap is catergory_id? An
attribute can be a category OF SOME KIND or an identifier of SOME
ENTITY, but it cannot be both. This is foundations, not rocket
science.
Alan, please get a book on data modeling and SQL! Oh, in MySQL current
version or a Standared SQL you might use " pet_type IN ('Cat', 'Dog',
'Hamster')|||David,
I had to modify the query because d.canonicalid does not exist and c can not
join d. When I joined table d to table e, I get rows returned, but the
Company "column" is the only one that is populated. Person and Product
contain only nulls.
Do you have any other suggestions, and thank you for the help.
Alan
"David Portas" wrote:

> "aslutsky" <aslutsky@.discussions.microsoft.com> wrote in message
> news:BE0AEB86-B15F-4E95-A13B-FBD7FFD748B4@.microsoft.com...
> Here's my best guess. Notice that I've removed the references to C2 and C3
> from the WHERE clause, otherwise the outer join effectively becomes and
> inner one - at least it does in standard SQL but I can't verify that for
> MySQL.
> SELECT DISTINCT c1.name AS dog, c2.name AS cat, c3.name AS hamster,
> d.title, d.identifier
> FROM Canonical c1
> LEFT JOIN Entity e1
> ON c1.canonicalid = e1.canonicalid
> LEFT JOIN Document d
> ON c1.canonicalid = d.canonicalid
> LEFT JOIN Entity e2
> ON c1.canonicalid = e2.canonicalid
> LEFT JOIN Canonical c2
> ON c1.canonicalid = c2.canonicalid
> AND c2.CategoryID='Cat'
> LEFT JOIN Canonical c3
> ON c1.canonicalid = c3.canonicalid
> AND c3.CategoryID='Hamster'
> WHERE c1.CategoryID='Dog' ;
> --
> David Portas, SQL Server MVP
> Whenever possible please post enough code to reproduce your problem.
> Including CREATE TABLE and INSERT statements usually helps.
> State what version of SQL Server you are using and specify the content
> of any error messages.
> SQL Server Books Online:
> http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
> --
>
>

Monday, March 19, 2012

Aggregator Transform bug or feature

Hi,

I have two input columns (both DT_I4) in a column collection to a Aggregator transform. Now I am doing a group by to one and Count to another column.

To my surprise the output's column datatype is changed for Count Transform (DT_UI8) and I have to put extra Data Conversion Transfrom to get my DT_I4 datatype back.

Is this a bug or feature.

Dharmbir

Dharmbir wrote:

Hi,

I have two input columns (both DT_I4) in a column collection to a Aggregator transform. Now I am doing a group by to one and Count to another column.

To my surprise the output's column datatype is changed for Count Transform (DT_UI8) and I have to put extra Data Conversion Transfrom to get my DT_I4 datatype back.

Is this a bug or feature.

Dharmbir

Feature. The aggregated columns are "new" to the dataflow, and a count can't be negative so they use the unsigned-integer datatype. I know, I hate it too, but that's the way it goes.

Thursday, March 8, 2012

Aggregate problem

I am getting the following error in my SQL.
Column 'dbo.ClientWorkerStatus.WorkerTypeID' is invalid in the select list
because it is not contained in either an aggregate function or the GROUP BY
clause.
My code is below. What I want to get is up to 1, 2 or 3 counts for one
ClientID as there are multiples in the ClientWorkerStatus table.
SELECT dbo.ClientWorkerStatus.ClientID,
Preferred = CASE
WHEN dbo.ClientWorkerStatus.WorkerTypeID = 0 THEN 1
ELSE 0
END,
Family = CASE
WHEN dbo.ClientWorkerStatus.WorkerTypeID = 1 THEN 1
ELSE 0
END,
Pool = CASE
WHEN dbo.ClientWorkerStatus.WorkerTypeID = 2 THEN 1
ELSE 0
END
FROM dbo.ClientWorkerStatus INNER JOIN
dbo.ClientWorkerLink ON dbo.ClientWorkerStatus.ClientID =
dbo.ClientWorkerLink.ClientID AND
dbo.ClientWorkerStatus.WorkerID = dbo.ClientWorkerLink.WorkerID
WHERE (dbo.ClientWorkerStatus.StatusEnd IS NULL OR
dbo.ClientWorkerStatus.StatusEnd > GETDATE()) AND
(dbo.ClientWorkerLink.Active = 1)
GROUP BY dbo.ClientWorkerStatus.ClientID
Thanks, DavidWhat aggregate?
Have you tried something like:
SELECT s.ClientID,
Preferred = CASE s.WorkerTypeID WHEN 0 THEN 1 ELSE 0 END,
Family = CASE s.WorkerTypeID WHEN 1 THEN 1 ELSE 0 END,
Pool = CASE s.WorkerTypeID WHEN 2 THEN 1 ELSE 0 END
FROM
dbo.ClientWorkerStatus s
INNER JOIN dbo.ClientWorkerLink l
ON s.ClientID = l.ClientID
AND s.WorkerID = l.WorkerID
WHERE
COALESCE(s.StatusEnd, '20300101') > GETDATE()
AND l.Active = 1
GROUP BY
s.ClientID,
CASE s.WorkerTypeID WHEN 0 THEN 1 ELSE 0 END,
CASE s.WorkerTypeID WHEN 1 THEN 1 ELSE 0 END,
CASE s.WorkerTypeID WHEN 2 THEN 1 ELSE 0 END
Without DDL, sample data and desired results, this is only a guess. See
http://www.aspfaq.com/5006 for info on providing details that will yield a
full solution.|||Hello, David
Is the ClientI=ADD column the primary key (or a unique key) in the
ClientWorkerStatus table ? If yes, you can safely add the
WorkerT=ADypeID column to the GROUP BY list, i.e:
SELECT [...]
GROUP BY dbo.ClientWorkerStatus.ClientI=ADD,
dbo.ClientWorkerStatus.WorkerT=ADypeID=20
Razvan|||Erase your group by at the end of your query.
You don't have any sum, avg, .... in your query. The group by clause is not
required.
Jonathan
"Razvan Socol" wrote:

> Hello, David
> Is the ClientI_D column the primary key (or a unique key) in the
> ClientWorkerStatus table ? If yes, you can safely add the
> WorkerT_ypeID column to the GROUP BY list, i.e:
> SELECT [...]
> GROUP BY dbo.ClientWorkerStatus.ClientI_D,
> dbo.ClientWorkerStatus.WorkerT_ypeID
> Razvan
>|||Yes, Aaron...your's worked. However I was also able to get it to work
by surrounding the CASE statements in the SELECT clause by SUM(...).
For example:
Preferred = SUM(CASE s.WorkerTypeID WHEN 0 THEN 1 ELSE 0 END), ...etc
I do want to group the results by ClientID because any one ClientID can
have more than 1 WorkerTypeID so I need the count of each.
Thanks.
David
*** Sent via Developersdex http://www.examnotes.net ***|||Please post DDL, so that people do not have to guess what the keys,
constraints, Declarative Referential Integrity, data types, etc. in
your schema are. Sample data is also a good idea, along with clear
specifications. It is very hard to debug code when you do not let us
see it.
You have absolutely no idea how to design a schema, do you?
You have columns named "-type_id" which make no sense. Look at the
ISO-11179 Standards.
You have table names that end with "-link", as if you were writing a
1970's navigation database.
You have table of status codes when status is a kind of attribute, not
an entity.
Then after all those FUNDAMENTAL errors, you do not have any aggregates
in the useless crap you posted.
dbo.ClientWorkerStatus.StatusE=ADnd > GETDATE()) <<
You might want to get enough basic SQL programming skills to write this
as:
COALESCE (foo_status_end_date, CURRENT_TIMESTAMP) >=3D CURRENT_TIMESTAMP
There is no such thing as a magical, universal "status": -- it is the
status of **something**. That getdate() is a proprietary syntax which
good SQL programmers avoid like lice. Learn the options in the
language so you can write them in SQL and not in some 3GL-style syntax.

Tuesday, March 6, 2012

AGGREGATE doesn't do MIN/MAX on textual columns

Hi,

Can anyone from MS exaplain why the AGGREGATE component doesn't allow you to select MIN/MAX when the column is DT_STR/DT_WSTR?

Thanks

Jamie

Anyone?

|||

Thanks Jamie.

Frankly, it did not seem like a common request for our core data warehousing scenarios - so it was not coded in from day one. During beta, a couple of customers did request it, but they were able to work around the issue using a script component. And, as I remember, becuase they had some additional processing to do once they had found the max string value, a script would have been needed at some point anyway.

Always interested to hear scenarios of course. Meanwhile, this would be an interesting DCR, but so far we have not had much demand.

Donald

However, as my Aunt once said to a salesman who suggested there was "no demand" for something she was seeking - "There is a demand standing right in front of you, young man!"

|||

OK thanks Donald. Sommeone on this forum was indeed asking for it and when he asked why it wasn't there I couldn't answer him. Eventually he used, as you say, a script component.

-Jamie

|||

That someone was me

I am implementing a DW/DM, where I collect data from ca. 25 different source systems / DW's. One case where I need max on varchar: In some cases, as I collect data on invoice row level, one invoice row is allocated to more than one cost center (1-n), and I somehow have to collect only one of the cost centers. The cost center data is in a varchar column, and thus I need some way to collect one of the many choices. For the sake of plausible validation, I always want to take value using same method (max or min, since they are easy to write into sql).. I know the proper way of collecting this kind of data would be at the cost center level, but let's not get into that.

In earlier DW implementations I have made (using Ascential/IBM Datastage), I had tens of cases where I had to take max/min of a varchar column.

It could easily be so that even if the data itself is numeric, it is stored in a varchar column, and I hate strong type casts, since I can never be sure if there could sometimes be text information as the column allows it. I have seen that also.

Not implementing max/min on varchar columns seems as a silly limitation in SSIS. In my opinion, this kind of features should be included in the basic transforms, so that there would be no need to always write short scripts - thats what was used in DTS.

IMHO Datastage / Informatica are much more user friendly than DTS in sense for not needing programming skills, I would really like to see SSIS to evolve more into that direction (which it already has, when comparing to DTS).

Markus

|||If you consider adding min/max aggregation of text values to the aggregate transform, while MS in the code consider adding first and last. Occasionally they are very helpful.|||

Guys,

You're more likely to get this functionality if you ask for it thru the proper channels. Click through here and vote, and add a comment

https://connect.microsoft.com/SQLServer/feedback/ViewFeedback.aspx?FeedbackID=131210

Anecdotes of why you need it are a huge help as well.

-Jamie

|||How about including it because it's valid transact-sql to use it on non-numeric fields?

It'd be better to allow for the aggregate functions to work as they are supposed to according to the MS Transact-SQL documentation. It's also better to use an aggregate transform in my package rather than having to query outside of the datastream to do something that should've been included in the first place.

For a given group of records, I want to, for instance, find the minimum text value in a column -- I shouldn't need a script to tell me that.|||

Phil Brammer wrote:

It'd be better to allow for the aggregate functions to work as they are supposed to according to the MS Transact-SQL documentation.

Why?

SSIS is an ETL-tool, not a relational database. Nowhere in the SSIS documentation does it state that there is any adherance to T-SQL, ANSI SQL or any other SQL dialect.

I agree that the AGGREGATE should allow min/max on string fields but my justification for that is because it is something useful for ETL developers, not because some other development platform supports it.

-Jamie

|||

Jamie Thomson wrote:

Phil Brammer wrote:

It'd be better to allow for the aggregate functions to work as they are supposed to according to the MS Transact-SQL documentation.

Why?

SSIS is an ETL-tool, not a relational database. Nowhere in the SSIS documentation does it state that there is any adherance to T-SQL, ANSI SQL or any other SQL dialect.

I agree that the AGGREGATE should allow min/max on string fields but my justification for that is because it is something useful for ETL developers, not because some other development platform supports it.

-Jamie

Actually, yes it does reference Transact-SQL. Read the MSDN page on aggregate transformations. For each operation in the aggregation, they state to read the Transact-SQL documentation for more information.

Granted, I see the exception on the min/max operations... I'm just providing yet another reason to include the functionality. I can also appreciate why it was left out... It's far easier to calculate min/max on a strictly numeric field, considering you have to do an expensive sort on non-numeric fields to determin min/max.

Phil|||

Phil Brammer wrote:

Jamie Thomson wrote:

Phil Brammer wrote:

It'd be better to allow for the aggregate functions to work as they are supposed to according to the MS Transact-SQL documentation.

Why?

SSIS is an ETL-tool, not a relational database. Nowhere in the SSIS documentation does it state that there is any adherance to T-SQL, ANSI SQL or any other SQL dialect.

I agree that the AGGREGATE should allow min/max on string fields but my justification for that is because it is something useful for ETL developers, not because some other development platform supports it.

-Jamie

Actually, yes it does reference Transact-SQL. Read the MSDN page on aggregate transformations. For each operation in the aggregation, they state to read the Transact-SQL documentation for more information.

Phil Brammer wrote:

Does it? Then I stand corrected.

I personally think that's a bad idea because of the reasons elucidated in my last post in this thread, but hey!

Granted, I see the exception on the min/max operations... I'm just providing yet another reason to include the functionality. I can also appreciate why it was left out... It's far easier to calculate min/max on a strictly numeric field, considering you have to do an expensive sort on non-numeric fields to determin min/max.

Phil

true!

-J

|||

All,

The original feedback item was posted under the wrong category so I've re-posted here: https://connect.microsoft.com/SQLServer/feedback/ViewFeedback.aspx?FeedbackID=246223

Thanks to Phil for pointing it out.

-Jamie

AGGREGATE doesn't do MIN/MAX on textual columns

Hi,

Can anyone from MS exaplain why the AGGREGATE component doesn't allow you to select MIN/MAX when the column is DT_STR/DT_WSTR?

Thanks

Jamie

Anyone?

|||

Thanks Jamie.

Frankly, it did not seem like a common request for our core data warehousing scenarios - so it was not coded in from day one. During beta, a couple of customers did request it, but they were able to work around the issue using a script component. And, as I remember, becuase they had some additional processing to do once they had found the max string value, a script would have been needed at some point anyway.

Always interested to hear scenarios of course. Meanwhile, this would be an interesting DCR, but so far we have not had much demand.

Donald

However, as my Aunt once said to a salesman who suggested there was "no demand" for something she was seeking - "There is a demand standing right in front of you, young man!"

|||

OK thanks Donald. Sommeone on this forum was indeed asking for it and when he asked why it wasn't there I couldn't answer him. Eventually he used, as you say, a script component.

-Jamie

|||

That someone was me

I am implementing a DW/DM, where I collect data from ca. 25 different source systems / DW's. One case where I need max on varchar: In some cases, as I collect data on invoice row level, one invoice row is allocated to more than one cost center (1-n), and I somehow have to collect only one of the cost centers. The cost center data is in a varchar column, and thus I need some way to collect one of the many choices. For the sake of plausible validation, I always want to take value using same method (max or min, since they are easy to write into sql).. I know the proper way of collecting this kind of data would be at the cost center level, but let's not get into that.

In earlier DW implementations I have made (using Ascential/IBM Datastage), I had tens of cases where I had to take max/min of a varchar column.

It could easily be so that even if the data itself is numeric, it is stored in a varchar column, and I hate strong type casts, since I can never be sure if there could sometimes be text information as the column allows it. I have seen that also.

Not implementing max/min on varchar columns seems as a silly limitation in SSIS. In my opinion, this kind of features should be included in the basic transforms, so that there would be no need to always write short scripts - thats what was used in DTS.

IMHO Datastage / Informatica are much more user friendly than DTS in sense for not needing programming skills, I would really like to see SSIS to evolve more into that direction (which it already has, when comparing to DTS).

Markus

|||If you consider adding min/max aggregation of text values to the aggregate transform, while MS in the code consider adding first and last. Occasionally they are very helpful.|||

Guys,

You're more likely to get this functionality if you ask for it thru the proper channels. Click through here and vote, and add a comment

https://connect.microsoft.com/SQLServer/feedback/ViewFeedback.aspx?FeedbackID=131210

Anecdotes of why you need it are a huge help as well.

-Jamie

|||How about including it because it's valid transact-sql to use it on non-numeric fields?

It'd be better to allow for the aggregate functions to work as they are supposed to according to the MS Transact-SQL documentation. It's also better to use an aggregate transform in my package rather than having to query outside of the datastream to do something that should've been included in the first place.

For a given group of records, I want to, for instance, find the minimum text value in a column -- I shouldn't need a script to tell me that.|||

Phil Brammer wrote:

It'd be better to allow for the aggregate functions to work as they are supposed to according to the MS Transact-SQL documentation.

Why?

SSIS is an ETL-tool, not a relational database. Nowhere in the SSIS documentation does it state that there is any adherance to T-SQL, ANSI SQL or any other SQL dialect.

I agree that the AGGREGATE should allow min/max on string fields but my justification for that is because it is something useful for ETL developers, not because some other development platform supports it.

-Jamie

|||

Jamie Thomson wrote:

Phil Brammer wrote:

It'd be better to allow for the aggregate functions to work as they are supposed to according to the MS Transact-SQL documentation.

Why?

SSIS is an ETL-tool, not a relational database. Nowhere in the SSIS documentation does it state that there is any adherance to T-SQL, ANSI SQL or any other SQL dialect.

I agree that the AGGREGATE should allow min/max on string fields but my justification for that is because it is something useful for ETL developers, not because some other development platform supports it.

-Jamie

Actually, yes it does reference Transact-SQL. Read the MSDN page on aggregate transformations. For each operation in the aggregation, they state to read the Transact-SQL documentation for more information.

Granted, I see the exception on the min/max operations... I'm just providing yet another reason to include the functionality. I can also appreciate why it was left out... It's far easier to calculate min/max on a strictly numeric field, considering you have to do an expensive sort on non-numeric fields to determin min/max.

Phil|||

Phil Brammer wrote:

Jamie Thomson wrote:

Phil Brammer wrote:

It'd be better to allow for the aggregate functions to work as they are supposed to according to the MS Transact-SQL documentation.

Why?

SSIS is an ETL-tool, not a relational database. Nowhere in the SSIS documentation does it state that there is any adherance to T-SQL, ANSI SQL or any other SQL dialect.

I agree that the AGGREGATE should allow min/max on string fields but my justification for that is because it is something useful for ETL developers, not because some other development platform supports it.

-Jamie

Actually, yes it does reference Transact-SQL. Read the MSDN page on aggregate transformations. For each operation in the aggregation, they state to read the Transact-SQL documentation for more information.

Phil Brammer wrote:

Does it? Then I stand corrected.

I personally think that's a bad idea because of the reasons elucidated in my last post in this thread, but hey!

Granted, I see the exception on the min/max operations... I'm just providing yet another reason to include the functionality. I can also appreciate why it was left out... It's far easier to calculate min/max on a strictly numeric field, considering you have to do an expensive sort on non-numeric fields to determin min/max.

Phil

true!

-J

|||

All,

The original feedback item was posted under the wrong category so I've re-posted here: https://connect.microsoft.com/SQLServer/feedback/ViewFeedback.aspx?FeedbackID=246223

Thanks to Phil for pointing it out.

-Jamie

AGGREGATE doesn't do MIN/MAX on textual columns

Hi,

Can anyone from MS exaplain why the AGGREGATE component doesn't allow you to select MIN/MAX when the column is DT_STR/DT_WSTR?

Thanks

Jamie

Anyone?

|||

Thanks Jamie.

Frankly, it did not seem like a common request for our core data warehousing scenarios - so it was not coded in from day one. During beta, a couple of customers did request it, but they were able to work around the issue using a script component. And, as I remember, becuase they had some additional processing to do once they had found the max string value, a script would have been needed at some point anyway.

Always interested to hear scenarios of course. Meanwhile, this would be an interesting DCR, but so far we have not had much demand.

Donald

However, as my Aunt once said to a salesman who suggested there was "no demand" for something she was seeking - "There is a demand standing right in front of you, young man!"

|||

OK thanks Donald. Sommeone on this forum was indeed asking for it and when he asked why it wasn't there I couldn't answer him. Eventually he used, as you say, a script component.

-Jamie

|||

That someone was me

I am implementing a DW/DM, where I collect data from ca. 25 different source systems / DW's. One case where I need max on varchar: In some cases, as I collect data on invoice row level, one invoice row is allocated to more than one cost center (1-n), and I somehow have to collect only one of the cost centers. The cost center data is in a varchar column, and thus I need some way to collect one of the many choices. For the sake of plausible validation, I always want to take value using same method (max or min, since they are easy to write into sql).. I know the proper way of collecting this kind of data would be at the cost center level, but let's not get into that.

In earlier DW implementations I have made (using Ascential/IBM Datastage), I had tens of cases where I had to take max/min of a varchar column.

It could easily be so that even if the data itself is numeric, it is stored in a varchar column, and I hate strong type casts, since I can never be sure if there could sometimes be text information as the column allows it. I have seen that also.

Not implementing max/min on varchar columns seems as a silly limitation in SSIS. In my opinion, this kind of features should be included in the basic transforms, so that there would be no need to always write short scripts - thats what was used in DTS.

IMHO Datastage / Informatica are much more user friendly than DTS in sense for not needing programming skills, I would really like to see SSIS to evolve more into that direction (which it already has, when comparing to DTS).

Markus

|||If you consider adding min/max aggregation of text values to the aggregate transform, while MS in the code consider adding first and last. Occasionally they are very helpful.|||

Guys,

You're more likely to get this functionality if you ask for it thru the proper channels. Click through here and vote, and add a comment

https://connect.microsoft.com/SQLServer/feedback/ViewFeedback.aspx?FeedbackID=131210

Anecdotes of why you need it are a huge help as well.

-Jamie

|||How about including it because it's valid transact-sql to use it on non-numeric fields?

It'd be better to allow for the aggregate functions to work as they are supposed to according to the MS Transact-SQL documentation. It's also better to use an aggregate transform in my package rather than having to query outside of the datastream to do something that should've been included in the first place.

For a given group of records, I want to, for instance, find the minimum text value in a column -- I shouldn't need a script to tell me that.|||

Phil Brammer wrote:

It'd be better to allow for the aggregate functions to work as they are supposed to according to the MS Transact-SQL documentation.

Why?

SSIS is an ETL-tool, not a relational database. Nowhere in the SSIS documentation does it state that there is any adherance to T-SQL, ANSI SQL or any other SQL dialect.

I agree that the AGGREGATE should allow min/max on string fields but my justification for that is because it is something useful for ETL developers, not because some other development platform supports it.

-Jamie

|||

Jamie Thomson wrote:

Phil Brammer wrote:

It'd be better to allow for the aggregate functions to work as they are supposed to according to the MS Transact-SQL documentation.

Why?

SSIS is an ETL-tool, not a relational database. Nowhere in the SSIS documentation does it state that there is any adherance to T-SQL, ANSI SQL or any other SQL dialect.

I agree that the AGGREGATE should allow min/max on string fields but my justification for that is because it is something useful for ETL developers, not because some other development platform supports it.

-Jamie

Actually, yes it does reference Transact-SQL. Read the MSDN page on aggregate transformations. For each operation in the aggregation, they state to read the Transact-SQL documentation for more information.

Granted, I see the exception on the min/max operations... I'm just providing yet another reason to include the functionality. I can also appreciate why it was left out... It's far easier to calculate min/max on a strictly numeric field, considering you have to do an expensive sort on non-numeric fields to determin min/max.

Phil|||

Phil Brammer wrote:

Jamie Thomson wrote:

Phil Brammer wrote:

It'd be better to allow for the aggregate functions to work as they are supposed to according to the MS Transact-SQL documentation.

Why?

SSIS is an ETL-tool, not a relational database. Nowhere in the SSIS documentation does it state that there is any adherance to T-SQL, ANSI SQL or any other SQL dialect.

I agree that the AGGREGATE should allow min/max on string fields but my justification for that is because it is something useful for ETL developers, not because some other development platform supports it.

-Jamie

Actually, yes it does reference Transact-SQL. Read the MSDN page on aggregate transformations. For each operation in the aggregation, they state to read the Transact-SQL documentation for more information.

Phil Brammer wrote:

Does it? Then I stand corrected.

I personally think that's a bad idea because of the reasons elucidated in my last post in this thread, but hey!

Granted, I see the exception on the min/max operations... I'm just providing yet another reason to include the functionality. I can also appreciate why it was left out... It's far easier to calculate min/max on a strictly numeric field, considering you have to do an expensive sort on non-numeric fields to determin min/max.

Phil

true!

-J

|||

All,

The original feedback item was posted under the wrong category so I've re-posted here: https://connect.microsoft.com/SQLServer/feedback/ViewFeedback.aspx?FeedbackID=246223

Thanks to Phil for pointing it out.

-Jamie

Aggregate Concatinate in join

Is table2 supposed to have a name column where a row in table 1 corresponds a
row in table 2 where the id's are equal?
try this it will create the table and populate it with your data from the
other tables.
select rtrim(a.name)+','+b.name as names, a.id as id, b.[date] as [date]
into table3 from table1 as a inner join table2 as b on (a.id=b.id)
if the other tables are being updated or used by apps then you can use a
view... create view as remove the 'into table3'
Hope it helps,
Netmon
"jobs" wrote:

> I have a two tables:
> table1
> id
> name
> table2
> id
> date
> I'd like to produce
> table3:
> id names date
> where names = all names for the id concatinated seperated by ","
>
Netmon wrote:

> Is table2 supposed to have a name column where a row in table 1 corresponds a
> row in table 2 where the id's are equal?
> try this it will create the table and populate it with your data from the
> other tables.
> select rtrim(a.name)+','+b.name as names, a.id as id, b.[date] as [date]
> into table3 from table1 as a inner join table2 as b on (a.id=b.id)
> if the other tables are being updated or used by apps then you can use a
> view... create view as remove the 'into table3'
> Hope it helps,
> Netmon
>
> "jobs" wrote:
>
[vbcol=seagreen]
In SQL Server 2005 you can do like this
select distinct a.id , stuff((select ','+name as [text()] from a as b
where a.id = b.id for xml path('')),1,1,'') as names,
b.date
from a inner join b on a.id = b.id
Regards
Amish Shah

Aggregate column comparison in sql server sql ?

I am no expert in sql, but I keep stubbling on this problem:

I have a table t1 with 2 columns (a,b)
I have a table t2 with 2 columns (c,d)

I need to delete all records from t1 which have the same value (a,b)
than the value of (c,d) in all records in the t2 table.

I oracle, this is simple:

delete from t1
where (a,b) in (select c,d from t2)

because Oracle has support for this syntax. Dont remember how they call
it. But this is not support in sql server. So I have to resort to:

delete from t1
where a + '+' + b in ( select c + '+' + d from t2)

Of course, a,b,c,d must be varchar for this to work. Basically I fake a
unique key for the records. Is there a better way to do this?

ThanksDELETE FROM T1
WHERE EXISTS
(SELECT *
FROM T2
WHERE T1.a = T2.c
AND T1.b = T2.d) ;

--
David Portas
SQL Server MVP
--|||David Portas (REMOVE_BEFORE_REPLYING_dportas@.acm.org) writes:
> DELETE FROM T1
> WHERE EXISTS
> (SELECT *
> FROM T2
> WHERE T1.a = T2.c
> AND T1.b = T2.d) ;

Which should be added, is a syntax that also works in Oracle.

Then again the syntax with IN that Oracle has is, as far as I know,
ANSI-compliant, so SQL Server is at fault here.

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||Which re-inforce our local beleive:

Oracle supperior SQL and performance
SQL Server, superior tools for users.

Everybody predicts Oracle downfall because of their reluctance to give
tools like TOAD for free.

The corporate battle must go on!

Saturday, February 25, 2012

Aggregate (SUM) a column and then use the Result?

Hi,

I am importing some data from Excel. I have to SUM one of the columns, and then use the result of the sum to calculate the percentages of each row. How can I use the Aggregate to give me a total of a column, so that i can use the total in another task and use formulas to calculate the percentages? i have tried to use multicast and join, but I get an extra row with the sum, which is not what I want; I want to use the sum for all the data.

Thanks

What about using an Execute SQL task in the control flow to put that value into a variable; then you can use that variable in the data flow and perform the calculation using a derived column. This thread explains how to run queries against an excel file: http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=772416&SiteID=1

|||

Fawad wrote:

Hi,

I am importing some data from Excel. I have to SUM one of the columns, and then use the result of the sum to calculate the percentages of each row. How can I use the Aggregate to give me a total of a column, so that i can use the total in another task and use formulas to calculate the percentages? i have tried to use multicast and join, but I get an extra row with the sum, which is not what I want; I want to use the sum for all the data.

Thanks

Seems to me you're going about this the wrong way. You need to calculate the SUM first and THEN use it in your data-flow. Hence, this is two executables (i.e. tasks) in your package. Rafael gave an example of doing this.

-Jamie

|||Hi Jamie,

I understand the flow:

Load Data
Calculate the Sum
Calculate new columns based on the sum (mostly count_value/total to get the rate)
Insert the final data into database.

What I cannot figure out is how to do the sum as an aggregate and then use it to do the computation.

Fawad
|||Hi Jamie,

I understand the flow that I require:

Import data from Excel
Sum the one column
Use this sum to calculate new column (mostly rates)
Load in the database

What I cannot figure out is how to use the result of the sum from the aggregate task.

Fawad
|||

Jamie Thomson wrote:

Fawad wrote:

Hi,

I am importing some data from Excel. I have to SUM one of the columns, and then use the result of the sum to calculate the percentages of each row. How can I use the Aggregate to give me a total of a column, so that i can use the total in another task and use formulas to calculate the percentages? i have tried to use multicast and join, but I get an extra row with the sum, which is not what I want; I want to use the sum for all the data.

Thanks

Seems to me you're going about this the wrong way. You need to calculate the SUM first and THEN use it in your data-flow. Hence, this is two executables (i.e. tasks) in your package. Rafael gave an example of doing this.

-Jamie

Hi Jamie,

I understand the flow
Load from Excel file
Use aggregate to calculate the SUM
Use the SUM to calculate the values for other columns (mostly rates)
Insert the data into a DB

What I do not understand is how to use the result of the Sum (its one value, think of select sum(field) from table) to calculate the other values.

Fawad
|||

Fawad wrote:

Jamie Thomson wrote:

Fawad wrote:

Hi,

I am importing some data from Excel. I have to SUM one of the columns, and then use the result of the sum to calculate the percentages of each row. How can I use the Aggregate to give me a total of a column, so that i can use the total in another task and use formulas to calculate the percentages? i have tried to use multicast and join, but I get an extra row with the sum, which is not what I want; I want to use the sum for all the data.

Thanks

Seems to me you're going about this the wrong way. You need to calculate the SUM first and THEN use it in your data-flow. Hence, this is two executables (i.e. tasks) in your package. Rafael gave an example of doing this.

-Jamie

Hi Jamie,

I understand the flow
Load from Excel file
Use aggregate to calculate the SUM
Use the SUM to calculate the values for other columns (mostly rates)
Insert the data into a DB

What I do not understand is how to use the result of the Sum (its one value, think of select sum(field) from table) to calculate the other values.

Fawad

Right. So Rafael's suggestion is exactly how you should attempt to do this.

-Jamie

|||

Fawad,

My sugestion was to use an Execute SQL task (control flow) to get the SUM value into a variable; it would be a query like Select Sum(yourcolumn) from [YourExcelSheet]. this step has to be done before the dataflow. Then the dataflow would have that value avilable and it could be used in a derived column.

Sunday, February 19, 2012

After Table Add Column

I have a situation. I am trying to add a column into a table called CUST but the command ALTER TABLE CUST ADD COLUMN PHONENUM VARCHAR(20) will only add a column to end of the column list. Does anyone know to add a column into a table in a specific location, like between two columns.

Another solution will be to use MMSQL Enterprise Manager but I want to add via a script. I have also noticed column can use the keyword BEFORE to specify a column name but for some reason this does not work in MSSQL2000.

Thanks a lot,

JTLike the location of data in a databse, the ordinal position of a column in a table doesn't matter...

and EM does a drop alert rename...you can see the script...

it'll look like:

BEGIN TRANSACTION
SET QUOTED_IDENTIFIER ON
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
COMMIT
BEGIN TRANSACTION
CREATE TABLE dbo.Tmp_myTable99
(
Col1 sysname NOT NULL,
Colx char(10) NULL,
Col2 sysname NOT NULL
) ON [PRIMARY]
GO
IF EXISTS(SELECT * FROM dbo.myTable99)
EXEC('INSERT INTO dbo.Tmp_myTable99 (Col1, Col2)
SELECT Col1, Col2 FROM dbo.myTable99 TABLOCKX')
GO
DROP TABLE dbo.myTable99
GO
EXECUTE sp_rename N'dbo.Tmp_myTable99', N'myTable99', 'OBJECT'
GO
COMMIT

EDIT: You know, I'm suprised it doesn't do a SELECT INTO instead...

ideas anyone?

Got have something to do with the catalog...|||I have done something similar to what you have and I thought there was something in MSSQL that easy the process. I am dealing with live database and I have over 200000 records on it. This is not an in house issue, therefore, I have write a script that will ask for some type parameters to pass to script and my script will do the rest.

This is my first version

use DOCUWARE

/************************************************** ********************************************/
/* */
/* Purpose: */
/* ~ To be able to insert-column in specific location within a DocuWare table */
/* Parameters are pass to ecript under the [PARAMETER] section. Designed only for MSSQL 2000*/
/* */
/* Parameters: */
/* @.tableNameToModify = Name of the table that you are going to modify */
/* @.newDataType = Enter the new datatype for the new column */
/* @.newDatatypeLenght = Enter the lenght of the datatype, for CHAR and VARCHAR only */
/* @.newName = Enter the name for the new column */
/* @.beforeColumn = Enter the name of a existing column, it will insert that new */
/* column before this column */
/* @.allowNull = 1 to allow blank spaces, if 0, user must enter data on this field */
/* */
/************************************************** ********************************************/

/*. . . .[ V A R I A B L E S ]. . . . */
declare @.tableNameToModify varchar(50),
@.newDataType varchar(50),
@.newDatatypeLenght integer,
@.newName varchar(50),
@.beforeColumn varchar(50),
@.objectId int,
@.allowNull int

/* . . . [ P A R A M E T E R S ] . . . */
select @.tableNameToModify = 'personal'
select @.newDataType = 'VARCHAR'
select @.newDatatypeLenght = 20 --> No more than 40 chars for DocuWare
select @.newName = 'SNN'
select @.beforeColumn = 'DOS'
select @.allowNull = 1 --> 0 = No, 1 = Yes

/*. . . .[ V A R I A B L E S ]. . . . */
declare @.seqNum integer,
@.colId integer,
@.holdEXEStatement varchar(5000),
@.colName varchar(50) ,
@.colDatatype varchar(50),
@.coldLength int,
@.isNullable int,
@.constraintType int,
@.seqIndex int,
@.seqStoper int,
@.stopCounter int,
@.maxNumber int,
@.guider int,
@.finalStoper int,
@.exeStoper int,
@.totalLen int,
@.holdNewColumns varchar(5000),
@.oldTableName varchar(20),
@.newTableName varchar(20),
@.alterTable varchar(200)

/* . . . [ E X E C U T I O N ] . . . */
SET ANSI_WARNINGS OFF
-- Check if the table exist
if exists (select 1 from sysobjects where name = upper(rtrim(@.tableNameToModify)))
begin

/* Select old columns and move to a tmp-table */
select @.objectId = id from sysobjects where name = upper(rtrim(@.tableNameToModify))
create table #holdColumns
(
seqNum integer,
colId integer,
colName varchar(50) ,
colDatatype varchar(50),
coldLength int,
isNullable int,
constraintType int
)
/*Create a cursor to retrive columns*/
declare c_cursor cursor for
select 1,
c.colid,
c.name,
t.name,
c.length,
c.isnullable,
s.status
from syscolumns c(nolock), systypes t(nolock), sysconstraints s(nolock)
where c.id = @.objectId
and c.xtype = t.xtype
and c.id = s.id
and c.name not in ('DW_FULLTEXT', 'DW_INDEXTIME', 'DW_REINDEXTIME', 'DW_ROWSTATE', 'DW_TIMESTAMP') -- not like '%DW_%'
order by c.colid asc
for read only
-- Start inserting the cursor
open c_cursor
-- Get the first one on the list
fetch next from c_cursor
into @.seqNum,
@.colId ,
@.colName ,
@.colDatatype ,
@.coldLength,
@.isNullable ,
@.constraintType
while @.@.fetch_status = 0
begin
-- Insert into a tmp table table
set nocount on
select @.seqIndex = @.seqIndex + 1
insert into #holdColumns
(seqNum, colId, colName, colDatatype, coldLength, isNullable, constraintType)
values (@.seqNum, @.colId, @.colName, @.colDatatype, @.coldLength, @.isNullable, @.constraintType)
-- Get the next one on the list
fetch next from c_cursor
into @.seqNum,
@.colId,
@.colName,
@.colDatatype,
@.coldLength,
@.isNullable,
@.constraintType
end
CLOSE c_cursor
deallocate c_cursor

-- Place in the right order
select @.seqStoper = colId from #holdColumns where colName = rtrim(upper(@.beforeColumn))
create table #rightOrder (
r_colId integer,
r_colName varchar(50),
r_colDatatype varchar(50),
r_lenght integer,
r_isNullable integer )

-- Insert new columns
select @.guider = min(colId) from #holdColumns
while (select colId from #holdColumns where colId = @.guider) <> @.seqStoper
begin
Insert into #rightOrder -- ( r_colId, r_colName, r_colDatatype, r_lenght, r_isNullable )
select colId, colName, colDatatype, coldLength, isNullable from #holdColumns where colId = @.guider
select @.guider = @.guider + 1
end
-- Insert the new column in the order that he user wants
insert into #rightOrder -- ( r_colId, r_colName, r_colDatatype, r_lenght, r_isNullable )
values ( @.guider, @.newName, lower(@.newDataType), @.newDatatypeLenght, @.allowNull)
-- Insert the last columns
select @.finalStoper = max(colId) + 1 from #holdColumns
while (select colId from #holdColumns where colId = @.guider) <> @.finalStoper
begin
Insert into #rightOrder -- ( r_colId, r_colName, r_colDatatype, r_lenght, r_isNullable )
select colId + 1, colName, colDatatype, coldLength, isNullable from #holdColumns where colId = @.guider
select @.guider = @.guider + 1
end

-- Create new table with new datatypes
create table #scriptTable (
scriptSeq integer,
tmpdata varchar(100))
insert #scriptTable
select r_colId, r_colName + case r_colDatatype when 'int' then ' INTEGER '
when 'datetime' then ' DATETIME '
when 'varchar' then ' VARCHAR(' + convert(varchar(5), r_lenght) + ')'

Thursday, February 16, 2012

After Restore Identity Column mess up

When restore the data from last night backup agter a server failure. My
identiy column values are mess up and showing a different id than was before.
I have this as primary key in my table and store into user station as cookies.
What is wrong an dhow to fix it.
Help desperate
Thansk
TanweerI don't know exactly what you are doing but I can't duplicate the problem you
are having. Something is amiss. Are you POSITIVE that your backup file
contains the IDENTITY values that you think they contain? Restore a test
database under a different name and check it out.|||I tried it on other database and they are ok however this database after a
disk crash is behaving like this.
Thanks
"Scagnetti" wrote:
> I don't know exactly what you are doing but I can't duplicate the problem you
> are having. Something is amiss. Are you POSITIVE that your backup file
> contains the IDENTITY values that you think they contain? Restore a test
> database under a different name and check it out.|||Disk crash... Any errors from DBCC CHECKDB?
--
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
"Tanweer" <Tanweer@.discussions.microsoft.com> wrote in message
news:07EE4B98-1A80-4606-95DB-3A7ABAF971C3@.microsoft.com...
>I tried it on other database and they are ok however this database after a
> disk crash is behaving like this.
> Thanks
>
> "Scagnetti" wrote:
>> I don't know exactly what you are doing but I can't duplicate the problem you
>> are having. Something is amiss. Are you POSITIVE that your backup file
>> contains the IDENTITY values that you think they contain? Restore a test
>> database under a different name and check it out.

After Restore Identity Column mess up

When restore the data from last night backup agter a server failure. My
identiy column values are mess up and showing a different id than was before
.
I have this as primary key in my table and store into user station as cookie
s.
What is wrong an dhow to fix it.
Help desperate
Thansk
TanweerI don't know exactly what you are doing but I can't duplicate the problem yo
u
are having. Something is amiss. Are you POSITIVE that your backup file
contains the IDENTITY values that you think they contain? Restore a test
database under a different name and check it out.|||I tried it on other database and they are ok however this database after a
disk crash is behaving like this.
Thanks
"Scagnetti" wrote:

> I don't know exactly what you are doing but I can't duplicate the problem
you
> are having. Something is amiss. Are you POSITIVE that your backup file
> contains the IDENTITY values that you think they contain? Restore a test
> database under a different name and check it out.|||Disk crash... Any errors from DBCC CHECKDB?
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
"Tanweer" <Tanweer@.discussions.microsoft.com> wrote in message
news:07EE4B98-1A80-4606-95DB-3A7ABAF971C3@.microsoft.com...[vbcol=seagreen]
>I tried it on other database and they are ok however this database after a
> disk crash is behaving like this.
> Thanks
>
> "Scagnetti" wrote:
>

After Restore Identity Column mess up

When restore the data from last night backup agter a server failure. My
identiy column values are mess up and showing a different id than was before.
I have this as primary key in my table and store into user station as cookies.
What is wrong an dhow to fix it.
Help desperate
Thansk
Tanweer
I don't know exactly what you are doing but I can't duplicate the problem you
are having. Something is amiss. Are you POSITIVE that your backup file
contains the IDENTITY values that you think they contain? Restore a test
database under a different name and check it out.
|||I tried it on other database and they are ok however this database after a
disk crash is behaving like this.
Thanks
"Scagnetti" wrote:

> I don't know exactly what you are doing but I can't duplicate the problem you
> are having. Something is amiss. Are you POSITIVE that your backup file
> contains the IDENTITY values that you think they contain? Restore a test
> database under a different name and check it out.
|||Disk crash... Any errors from DBCC CHECKDB?
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
"Tanweer" <Tanweer@.discussions.microsoft.com> wrote in message
news:07EE4B98-1A80-4606-95DB-3A7ABAF971C3@.microsoft.com...[vbcol=seagreen]
>I tried it on other database and they are ok however this database after a
> disk crash is behaving like this.
> Thanks
>
> "Scagnetti" wrote: