Updating Values During SELECT Using CTE And Row_Number()
Sep 19, 2007
Hi,
I'm very new to stored procedures and I've been searching on google to find a way to custom page my results using SQL Server 2005. I'm trying to use Row_Number() and a CTE to keep things efficient and scaleable but I keep getting an error next to my UPDATE statement.
I get the following error: "[Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near the keyword 'UPDATE'."
The sproc works without the UPDATE statement. Does anyone know where I need to put the UPDATE statement to update the "searched" field for each record selected?
CREATE PROCEDURE [zk_update_request_england]
(
@property_type tinyint,
@market_status tinyint,
@price int,
@bedrooms tinyint,
@search_location varchar(30),
@search_district varchar(30),
@PageSize int,
@PageIndex int
)
AS
BEGIN
WITH SearchResults AS
(
UPDATE dbo.zk_request_england
SET searched = searched + 1
WHERE property_type = @property_type
AND market_status = @market_status
AND bedrooms = @bedrooms
AND search_location = @search_location
AND search_district = @search_district
AND min_price <= @price
AND max_price >= @price
SELECT user_id,
min_price,
max_price,
property_description,
searched,
ROW_NUMBER() OVER (ORDER BY max_price DESC) AS RowNumber
FROM dbo.zk_request_england
WHERE property_type = @property_type
AND market_status = @market_status
AND bedrooms = @bedrooms
AND search_location = @search_location
AND search_district = @search_district
AND min_price <= @price
AND max_price >= @price
)
SELECT user_id,
min_price,
max_price,
property_description
FROM SearchResults
WHERE RowNumber BETWEEN (@PageIndex - 1) * @PageSize + 1 and @PageIndex*@PageSize
END
Thanks in advance for any help.
View 3 Replies
ADVERTISEMENT
Jun 9, 2008
here it is:
SELECT * FROM ( SELECT ROW_NUMBER() Over (Order By LastActivity ASC) As rn UserName) FROM aspnet_usersWhere rn = 1
it's saying: "Incorrect syntax near UserName"
all column/table names are correct
View 6 Replies
View Related
Sep 3, 2007
Hi,
Code Snippet
This is difficult to explain in words, but the following code outlines what I am trying to do:
with myTableWithRowNum as
(
select 'row' = row_number() over (order by insertdate desc), myValue
from
(
select table1Id As myValue from myTable1
union
select table2Id As myValue from myTable2
)
)
select * from myTableWithRowNum
Can anyone think of a work around so that I can use the Row_Number function where the data is coming from a union?
View 4 Replies
View Related
Feb 5, 2008
I have the following insert query which works great. The purpose of this query was to flatten out the Diagnosis codes (ex: SecDx1, SecDx2, etc.) [DX_Code field] in a table.
Code Snippet
INSERT INTO reports.Cardiology_Age55_Gender_ACUTEMI_ICD9
SELECT
Episode_Key,
SecDX1 = [1],
SecDX2 = [2],
SecDX3 = [3],
SecDX4 = [4],
SecDX5 = [5],
SecDX6 = [6],
SecDX7 = [7],
SecDX8 = [8],
SecDX9 = [9],
SecDX10 = [10],
SecDX11 = [11],
SecDX12 = [12],
SecDX13 = [13],
SecDX14 = [14],
SecDX15 = [15]
FROM (SELECT
Episode_Key, DX_Key,
ROW_NUMBER() OVER ( PARTITION BY Episode_Key ORDER BY DX_Key ) AS 'RowNumber', DX_Code
FROM srm.cdmab_dx_other
WHERE Episode_key is not null
) data
PIVOT
( max( DX_Code ) FOR RowNumber IN ( [1], [2], [3], [4], [5], [6],
[7], [8], [9], [10], [11], [12], [13], [14], [15] )) pvt
ORDER BY Episode_Key
The query below also works fine by itself. You may notice that the Episode_Key field appears in both the query above and below therefore providing a primary key / foreign key relationship. The srm.cdmab_dx_other table also appears in both queries. I would like to add the fields in the select statement below to the select statement above. Using the relationships in my FROM statements, can anyone help me figure this one out?
Code Snippet
SELECT
e.episode_key,
e.medrec_no,
e.account_number,
Isnull(ltrim(rtrim(p.patient_lname)) + ', ' ,'')
+
Isnull(ltrim(rtrim(p.patient_fname)) + ' ' ,'')
+
Isnull(ltrim(rtrim(p.patient_mname)) + ' ','')
+
Isnull(ltrim(rtrim(p.patient_sname)), '') AS PatientName,
CONVERT(CHAR(50), e.admission_date, 112) as Admit_Date,
CONVERT(CHAR(50), e.episode_date, 112) as Disch_Date,
e.episode_type as VisitTypeCode,
d.VisitTypeName,
convert(int, pm.PatientAge) as PatientAge,
pm.PatientAgeGroup,
pm.patientsex,
p.race
FROM srm.episodes e inner join
srm.cdmab_dx_other dxo on dxo.episode_key=e.episode_key inner join
srm.cdmab_base_info cbi on cbi.episode_key=e.episode_key inner join
srm.item_header ih on ih.item_key = e.episode_key inner join
srm.patients p on p.patient_key = ih.logical_parent_key inner join
ampfm.dct_VisitType d on d.VisitTypeCode=e.episode_type inner join
dbo.PtMstr pm on pm.AccountNumber = e.Account_Number
View 3 Replies
View Related
Feb 4, 2008
Can anybody know ,how can we add builtin functions(ROW_NUMBER()) of Sql Server 2005 into database library.
I get this error when i used into storeprocedure :
ROW_NUMBER() function is not recognized in store procedure.
i used MS SQL SERVER 2005 , so i think "ROW_FUNCTION()" is not in MS SQL SERVER 2005 database library.
I need to add that function into MS SQL SERVER 2005 database library.
Can anbody know how we can add that function into MS SQL SERVER 2005 database library?
View 4 Replies
View Related
May 14, 2008
Hi!
I am trying to retrieve and update data. I am retrieving the data into the respective controls such as textboxes. The codes are follow:
Retrieve data - working
Dim sqlConn As New SqlConnection()
sqlConn.ConnectionString = ConfigurationManager.ConnectionStrings("ScheduleConnectionString").ToString()
Dim com As SqlCommand = New SqlCommand("SELECT * FROM Demo_Theatre_DB WHERE ID=" & "@ID", sqlConn)
Dim paramID As New SqlParameter("@ID", SqlDbType.Int)
paramID.Direction = ParameterDirection.Input
com.Parameters.Add(paramID)
paramID.Value = e.Value
sqlConn.Open()
Dim reader As SqlDataReader = com.ExecuteReader()
While reader.Read()
StartTimeTextBox.Text = reader("StartTime")
EndTimeTextBox.Text = reader("EndTime")
CompanyNameTextBox.Text = reader("CompanyName")
PurposeTextBox.Text = reader("Purpose")
AccountManagerTextBox.Text = reader("AccountManager")
PresenterTextBox.Text = reader("Presenter")
ColorDDL.SelectedValue = reader("ColorCode")
StatusRadioButtonList.SelectedValue = reader("Status")
CommentTextBox.Text = reader("Comments")
End While
update the data - NOT WORKING
Dim sqlConn As New SqlConnection()
sqlConn.ConnectionString = ConfigurationManager.ConnectionStrings("ScheduleConnectionString").ToString()
Dim cmd As SqlCommand = New SqlCommand("UPDATE Demo_Theatre_DB SET StartTime = @StartTime, EndTime = @EndTime, CompanyName = @CompanyName, Purpose = @Purpose, AccountManager = @AccountManager, Presenter = @Presenter, ColorCode = @ColorCode, Status = @Status, Comments = @Comments WHERE ID=@ID")
cmd.Parameters.AddWithValue("StartTime", StartTimeTextBox.Text)
cmd.Parameters.AddWithValue("EndTime", EndTimeTextBox.Text)
cmd.Parameters.AddWithValue("CompanyName", CompanyNameTextBox.Text)
cmd.Parameters.AddWithValue("Purpose", PurposeTextBox.Text)
cmd.Parameters.AddWithValue("AccountManager", AccountManagerTextBox.Text)
cmd.Parameters.AddWithValue("Presenter", PresenterTextBox.Text)
cmd.Parameters.AddWithValue("ColorCode", ColorDDL.SelectedValue)
cmd.Parameters.AddWithValue("Status", StatusRadioButtonList.SelectedValue)
cmd.Parameters.AddWithValue("Comments", CommentTextBox.Text)
Try
sqlConn.Open()
cmd.ExecuteScalar()
Catch ex As Exception
InsertMsgLabel.Text = ex.ToString
End Try
End Sub
I am getting the following error whenever I click update button.
"ExecuteScalar: Connection property has not been initialized"
Your help will be appriciated!
Thanks!
View 24 Replies
View Related
Mar 9, 2004
I have table A which has and accountid,df_date1,df_date2. The table is a demographic one which has 1 record for each account
I have a table B which I need to populate from the first df_date1 fields in table A. Table B which is normalized and has an accountid and a df_date1 field but may have several records per accountid. I need the max(date) from this table. I wanted to do an update statement like below
update A
set df_date1
= max(df_date1) from b
where a.account_id = b.account_id
I get the error message
Server: Msg 157, Level 15, State 1, Line 3
An aggregate may not appear in the set list of an UPDATE statement.
Is there another way to do this with a subselect and update?
View 2 Replies
View Related
Jun 23, 2008
how to use update statement to update fields in a table that has Null values
update sheet1 set [Middle Initial]='' where isnull([Middle Initial],'')=''
this statement some times works sometimes not.
View 7 Replies
View Related
Nov 7, 2007
I have a table named 'Personal' that has a field that contains values that represent colors (ex: BLACK, BROWN, BLUE, etc.). How do I run an update statement to update the values to defined set. For example (BLACK = BLK, BLUE = BLU, etc.)?
Thanks
View 5 Replies
View Related
Nov 16, 2007
Hi
I'm new to SQL and have a problem with the following script:-
INSERT INTO organisation_links (organisation_number_1, organisation_number_2, relationship, amended_on, amended_by)
VALUES 2311, 19219, 'BRAN', '01/12/2007', 'Jon')
The above script works OK on a one-off basis but....
Basically, organisation_number_2 (i.e. 19219) always stays the same. However, I need to update organisation_number_1 several times (i.e. 2311 will then change to 2312, 2313, 2314 etc.).
Rather than pasting the script several hundred times and changing the organisation_number_1 value each time, is there a quick way to encompass all the organisation_number_1 values in one go?
I've tried e.g. VALUES (2311,2312), 19219, 'BRAN' etc. but this doesn't seem to work.
Thanks for your help.
Jon
View 6 Replies
View Related
Feb 14, 2008
I have a table like that:
ColumnA ColumnB ColumnC
-------------------------------
Alice Lukas Alice.Lucas
James Redford James.Redford
James Redford James.Redford
Michael Jackson Michael.Jackson
John Brown John.Brown
John Brown John.Brown
John Brown John.Brown
George Gotham George.Gotham
I want to update duplicated values at ColumnC like:
Alice Lukas Alice.Lucas
James Redford James.Redford
James Redford James.Redford1
Michael Jackson Michael.Jackson
John Brown John.Brown
John Brown John.Brown1
John Brown John.Brown2
George Gotham George.Gotham
How can i do it?
Thanks in advance!
Note: Table is for creating email aliases from names...
View 2 Replies
View Related
May 2, 2008
SELECT
#followups.suspectid,
#followups.planid,
cond4,
cond5,
cond6,
cond7,
cond8,
tbpdmmembers.firstname tbpdmmembers_firstname,
dbo.GetMemID_PartC_D(#followups.hic,#followups.IsPart_C) tbpdmmembers_MemberID,
--tbpdmmembers.Plan1 tbpdmmembers_MemberID,
tbaddress.address1 tbaddress_address1,
tbaddress.address2 tbaddress_address2,
tbaddress.city tbaddress_city,
tbaddress.state tbaddress_state,
tbaddress.zip tbaddress_zip
from #followups
I want to check if the tbaddress.address1 tbaddress_address1 if it is =null or empty then make it = tbaddress.address2 tbaddress_address2, at the same time I make the tbaddress.address2 tbaddress_address2, null. Otherwise leave it as it is.
Actually, I am working with the report and the tbaddress.address1 carrying the apt number. if there is no aprt # then the line print blanks. so that brings the empty line between the street address and the citystate line.
That is what i am tryig to cover. There could be a way to do this from the crystal report but I am thinking of doing this way cause I can't get the solution to do it from the crystal report.
View 5 Replies
View Related
May 16, 2008
Hello, I have been SSIS for a bit now, but really only it its most straight forward simple tasks I have the following issue which for the life of me I can't seem to sort out
1)Excel Source - - -> all data pushed into a initial SQL table
2) Data in initial SQL table gets sorted, certain fields get made UPPER , right trim that sort of thing
3) now I select a set of distinct values of a certain column in the SQL table and get a list of maybe 60 results
these results I want to enter into a table in a different database on same server, the table in the destination db has a identity column and a value column
adding / appending all the distinct value from the import data works fine,
but I want to add only the values which are not already in the destination table what is the best way to update the destination table, should I be using stored proc or is there a easier way in SSIS to do this
Thanks
View 1 Replies
View Related
Apr 5, 2007
In my datawarehouse fact table I have a column (revenue) that I want to populate based on the values of number of columns, for simplicity, say just 2 columns, 'productid' and 'affiliateid'.
I have a revenue lookup table, with those same 2 columns and the amount. So far so simple, but rather than have one row for every possible combination, I use 0 to mean default. For instance, all the affiliates have the same revenue value apart from a couple, so instead of 200 rows identical except for the affiliateid, I have one row with a '0' for the affiliateid and 4 rows with specific affiliateIDs where it differs from the default.
E.G.
AffiliateID, TypeID, Revenue
0, 1, £50
22, 1, £55
33, 1, £57
0,2,£60
22, 2, £66
33, 2, £69
To update the values, I join to the revenues table twice, one for both columns matching, and once for the default. I.E.
UPDATE facttable SET revenue = ISNULL(rev1.revenue, ISNULL(rev2.revenue,0))
FROM facttable FT
LEFT OUTER JOIN revenues rev1 ON FT.AffiliateID = rev1.AffilateID and FT.TypeID = rev1.TypeID
LEFT OUTER JOIN revenues rev2 ON rev1.AffilateID = 0 and FT.TypeID = rev1.TypeID
(In fact, this is over-simplified, because in fact there are 3 columns, so I have to have 8 joins like this).
This works very well, and cuts down the management of revenues significantly, there are a few 100 rows instead of the more than 100,000 there would be if I put every possible combination of values in its own row.
However, now there is a requirement to increase the granularity of the revenue allocation up to 5 columns, which makes 36 joins and there could well be more columns added later.
Has anyone come across a situation like this (and found a neater solution).
View 2 Replies
View Related
Oct 13, 2007
Hi
I have a table containing:
ProductCat Product Qty NewQty
TypeA ProductA -10
TypeA ProductB 5
TypeB ProductX 8
TypeB ProductY -5
I need to get rid of negative values in the same ProductCat by adding surplus values to the negative values in the same ProductCat ie. This is what I ant the table to look like.
ProductCat Product Qty NewQty
TypeA ProductA -10 -5 (Add ProductB to ProductA in the same ProductCat to reduce the deficit)
TypeA ProductB 5 0 (Due to the fact that I added 5 to ProductA NewQty must be reduced by 5)
TypeB ProductX 8 3
TypeB ProductY -5 0 (Deficit only has to be reduced to 0 where possible therefor the balance
of 3 for ProductX)
Note the values in Qty can stay as the same. I am interested in the New values.
Could someone please help me with the correct method of doing this?
Thank you.
View 2 Replies
View Related
Oct 6, 2006
Im trying to update the values int the database and the query is executed correctly but database is not updated and the returned message is one, I really dont know whats causing this here is my code.1 private void UpdatetheDatabase(string connection)
2 {
3 SqlConnection connect = new SqlConnection(connection);
4 SqlCommand update_customer_details = new SqlCommand("UPDATE [app_CustomerDetails] " +
5 " SET [Name]=@Name,[City]=@City, " +
6 " WHERE [ID]=@ID", connect);
7 update_customer_details.Parameters.Add("@Name", SqlDbType.NVarChar, 50).Value = txtCustomerName.Text;
8 update_customer_details.Parameters.Add("@City", SqlDbType.NVarChar, 50).Value = txtCity.Text;
9 update_customer_details.Parameters.Add("@ID", SqlDbType.Int, 4).Value = ID;
10 connect.Open();
11 int x = update_customer_details.ExecuteNonQuery();
12 connect.Close();
13 StatusLabel.Text = x.ToString();
14 }
your help will be highly appreciated.
View 7 Replies
View Related
Oct 24, 2006
HiI am new to the world of aspx, .net and C#.In aspx .net 2.0. I am trying to work out how to get a datagrid to perform an update. Using Visual Developer I have successfully added the control and specifed a select statement to return data via my SQLData Source. This works fine. However having specifed the control as editable I would like to perform an update through the datagrid and SQLDatasource. I see in the properties for the SQLDatasource object I can specify my update statement.However I do not understand how to get that update statement to have variable values and how newly entered values from the grid can be placed into these variables when the update takes place. Can someone please point me in the right direction? I have not found the MS doc very illuminating thus far and have not found any examples.Many ThanksT
View 1 Replies
View Related
May 26, 2000
I am looking for suggestions on how to accomplish the following task with the least amount of hand keying that I can get away with.
I have a main table named Office and 4 other tables that have the Office table ID field value in them.
I have been given a new set of ID values that need to replace the values that are currently in the Office table and then update the ID field in the other 4 tables.
I have only thought of 2 solution and I don’t like either one.
1 Add a new column to the Office table and key in the new ID’s then go through the pages that reference the old ID field and change the SQL queries to use the new field.
2 Change the value of the current Office ID field to the new value. Search the other 4 tables for the old value and then update them to the new value.
Anyone got a better Idea?
View 1 Replies
View Related
Aug 25, 2004
Hello!
I have a "current" table which users update on a daily basis, it holds forecast data. This table is designed to only hold 7 days of data and is therfore always rolling over by date.
What I want to do is have a procedure that copies this "Current" table to a "History" table every day so the historical information is stored. The copy is simple, but how do I check for and over ride values that are already in the "history" table with the newest values from the "current" table because the "current" values have the possibility of changing a few times while the forecast is updated. I can define a primary key but am not sure how to check for and update the necessary values?
Any help??
Many thanks!
View 1 Replies
View Related
Nov 11, 2005
hi there,
i am new to sql server database.i am doing small projects right
now using asp.net and sql to create webpages (very basic webpages)
My problem is:
Problem :
i have two tables .....table 1 and table 2.
Table 1 has following fields: studentid,student name,student address.
Table 2 has following fields:studentid and course .
table1 student id is the primary key refrencing table 2 student id.
Now i delete a record in table 1 which will in turn also get deleted in
table 2 . so for eg if i have three records 1 ,2 and 3 ....then i
delete 2 in table 1 ...i will have 1 and 3 in both table 1 and table
2....now i want 3 to become 2 in both table 1 and table 2...so that i
dont have empty space between two student id's 1 and 3. so this is my
problem....if any one can help me out with suggestions please
do.
thank you all........
ahmed_ind
View 4 Replies
View Related
Mar 3, 2006
hi ,
I recently moved from SQL 2000 to SQL 2005.
The client side is vb6 and using Dcom dll's hosted on the db server.
I have a table which has oninsert trigger
When the recordset is updated in the com class it throws the foll error :
"Row cannot be located for updating. Some values may have been changed since it was last read."
The same code was working with SQL 2000 !!!
Any clues.
implicit tran are off on the sql 2005 server.
Thanks in advance.
View 2 Replies
View Related
May 2, 2008
Hi Folks,
I have a task I wrote which does not always update the property value (as seen in the properties pane)
Basically, change something on the form, then update the task host property with:
this.taskHostValue.Properties["Duration"].SetValue(this.taskHostValue, Convert.ToInt32(spnDuration.Value));
Stepping through this, it does exactly what it is supposed to. Having a look at the property value, it confirms it has changed.
Reopening the UI and resetting all the controls returns the expected results.
The package however does not realise it has changed. There is no * next to the package name in the top tabs.
As long as the package thinks it is unchanged, SaveXML does not get called either so the tasks do not persist.
Changing the value on the properties pane works fine though.
The frustrating thing is this is slightly random. Slight in the sense that sometimes it works but most of the time it does not.
The sample code I used was the MS download IncrementTask (Which works BTW) so I can't see it as being a VS / SSIS bug but rather something I am / am not doing. 3 tasks I have written all behave the same. I have to "nudge" them before savign the package.
Any ideas what the problem might be?
TIA
Cheers,
Crispin
View 3 Replies
View Related
May 19, 2006
How do I:Select f1, f2, f3, from tb1 where f1=Select f1 from tb2 where f1='condition'?
View 3 Replies
View Related
Apr 25, 2007
I am having an issue when trying to do something that looks simple on the face of it.. I want to replace the value during update in the same table.
Here's my situation
tst_update
ID int
Col1 varchar(10
I want to ensure that everytime Col1 is updated to "A" I want to set it to "X". Otherwise leave it as is.
Can someone help.
Thanks,
Ashish
View 6 Replies
View Related
Oct 24, 2006
I am attempting to update a sql db using the update and parameter code in VB.net 2003 through MSDE for a web application. It updates changed data OK, but if the textbox value is deleted, the code does not update the sql db. I am new to this, and I'm sure it is something simple. Here is some sample code.
SqlConnection1.Open()
strSQLu = "UPDATE table1 " _
& "SET Field1Tag = @Field1Tag, Field2Tag = @Field2Tag " _
& "WHERE (Field1Tag = @Field1Tag) "
cmdCategoriesUpdate.CommandText = strSQLu
With cmdCategoriesUpdate
.Parameters("@Field1Tag").Value = txtFld1.Text
.Parameters("@Field2Tag").Value = txtFld2.Text
End With
cmdCategoriesUpdate.ExecuteNonQuery()
SqlConnection1.Close()
View 3 Replies
View Related
Aug 19, 2003
Can I update a select query using sql server 2000? What I mean is, I want to use a query instead of table or a view.
eg update (select * from tablename) set field='value'
something of this sort. I tried doing some r&d but it didn't work. I want it as single query. If some one knows it please let me know. It is very urgent.
Regards,
Samir.
View 1 Replies
View Related
Jun 16, 2015
Here is a requirement. Need to update the columns in the tables with the latest values available in CSV.
The file is based on department so the list of tables which is under this department all the corresponding tables needs to updated.
The CSV file which is dynamic in nature the number of columns changes it has header of the columns that needs to be updated.
The destination tables are listed under department table for each department. So I have to update the columns in the tables with the values in csv.
View 4 Replies
View Related
Jan 8, 2001
Okay I'm going nuts.
I have a table with a max key value in it, and another table with a few rows in it. I'm trying to update the two new rows with key values that are iterative from the MAX value in the first table. Could anyone point me to some good LOOP...UPDATE, etc resources or pointers before I go postal?
::grins::
Example: first table has a key field, last value in it is say 1000. The second table has two records. They need keys too, and those keys need to start at the last value in the first table + 1, so 1001, and end on the last row of the second table, or, say 1002. I cannot figure out how to read the last value of the first table, and create an update loop to iteratively update the key value in the second table based on the max value of the first, and looping based on the number of records in the second, in this case 2.
Arrrg!
~EHunter
View 4 Replies
View Related
Aug 19, 2015
I have a stored procedure that selects the unique Name of an item from one table.Â
SELECT DISTINCT ChainName from Chains
For each ChainName, there exists 0 or more StoreNames in the Stores. I want to return the result of this select as the second field in each row of the result set.
SELECT DISTINCT StoreName FROM Stores WHERE Stores.ChainName = ChainName
Each row of the result set returned by the stored procedure would contain:
ChainName, Array of StoreNames (or comma separated strings or whatever)
How can I code a stored procedure to do this?
View 17 Replies
View Related
Jan 23, 2008
Hi,I have a query like this :SELECTx1,x2,( SELECT ... FROM ... WHERE ...UNIONSELECT ... FROM ... WHERE ...) as x3FROM ...WHERE ...The problem is that I don't want to return the results where x3 isNULL.Writing :SELECTx1,x2,( SELECT ... FROM ... WHERE ...UNIONSELECT ... FROM ... WHERE ...) as x3FROM ...WHERE ... AND x3 IS NOT NULLdoesn't work.The only solution I found is to write :SELECT * FROM((SELECTx1,x2,( SELECT ... FROM ... WHERE ...UNIONSELECT ... FROM ... WHERE ...) as x3FROM ...WHERE ...) AS R1)WHERE R1.x3 IS NOT NULLIs there a better solution? Can I use an EXISTS clause somewhere totest if x3 is null without having to have a 3rd SELECT statement?There's probably a very simple solution to do this, but I didn't findit.Thanks
View 7 Replies
View Related
May 28, 2008
Hi,
This is my view in Sql2005
SELECT DISTINCT VLAN8, 'CONV' AS VLEDUS, MAX(CAST(VLEDBT AS int)) AS MaxVLEDBT
FROM JDE_DEVELOPMENT.TESTDTA.F06116Z1
GROUP BY VLAN8, VLEDUS
2111CONV2111
4803CONV31
7550CONV33
When I add row number function the results become wrong:
SELECT DISTINCT VLAN8, 'CONV' AS VLEDUS, ROW_NUMBER() OVER (ORDER BY VLAN8) AS VLEDLN, MAX(CAST(VLEDBT AS int)) AS MaxVLEDBT
FROM JDE_DEVELOPMENT.TESTDTA.F06116Z1
GROUP BY VLAN8, VLEDUS, VLEDLN
2111 CONV 1 2111
4803 CONV 2 31
4803CONV3 31
4803CONV4 31
4803CONV5 31
4803CONV6 31
4803CONV7 31
4803CONV8 31
4803CONV931
4803CONV1031
4803CONV1131
4803CONV1231
7550CONV1333
7550CONV1433
7550CONV1533
7550CONV1633
I just need to have :
2111CONV 1 2111
4803CONV 2 31
7550CONV 3 33
Please help me.
View 6 Replies
View Related
Sep 14, 2007
I'm using SQL Server 2005, sp 2. My query is below. What I want to see for the results is the average of all of partition 1, the average of partition 2, etc. Does anybody know how I can get this?
SELECT ROW_NUMBER() OVER (PARTITION BY Shop.Location_Code ORDER BY Shop.Date_Code) AS [PARTITION],
(Score) AS [This Year], Shop.Date_Code, Shop.Location_Code
FROM ETL.Transform_FactOpsMSScorecard SHOP INNER JOIN DW_DatamartDB.dbo.DimDate DD
ON Shop.Date_Code=DD.Date_Code
INNER JOIN DW_DatamartDB.dbo.DimLocation LOC ON
Shop.Location_Code = Loc.Location_Code
WHERE District_Code = (@District)
Results:
Partition This Year Date Code Location Code
1 .85 20070101 1
2 .58 20070509 1
1 .52 20070808 2
2 .54 20070905 2
3 .26 20070104 3
3 .26 20070905 3
View 4 Replies
View Related
Jan 21, 2008
Hi,
After I read some article about Row_Number() and CTE, I still don't know What they are used for.
Can anyone explain to you?
Thank you
View 9 Replies
View Related