SQL Server 2012 :: How To Choose Max Of Each Groups Formed By Row Number
Sep 15, 2015
I have a below table as:
IF OBJECT_ID('tempdb..#Test') IS NOt NULL
DROP TABLe #Test
--===== Create the test table with
create table #Test([Year] float,
Age Int,
)
INSERT INTO #Test
([Year], Age)
[Code]...
I queried below to get additional column
Select *,row_number() over(partition by [Year] order by Age) as RN from #Test as
YearAgeRN
2014301
2014312
2014323
2015251
2015262
2015273
2015284
2015295
i want one more addtional column (Desired Output) with max of RN in each group as below"
YearAgeRNDesired output
20152515
20152625
20152735
20152845
20152955
20143013
20143123
20143233
View 7 Replies
ADVERTISEMENT
Jun 15, 2015
I need to calculate the last two columns (noofgrp and grpsize) No of Groups (count of Clientid) and Group Size (number of clients in each group) according to begtim and endtime. So I tried the following in the first Temp table
GrpSize= count(clientid) over (partition by begtime,endtime) else 0 end
and in the second Temp Table, I have
select
,GrpSize=sum(grpsize)
,NoofGrp=count(distinct grpsize)
From Temp1
The issue is for the date of 5/26, the begtime and endtime are not consistent. in Grp1 (group 1) all clients starts the session at 1030 and ends at 1200 (90 minutes session) except one who starts at 11 and end at 1200 (row 8). For this client since his/her endtime is the same as others, I want that client to be in the first group(Grp1). Reverse is true for the second group (Grp2). All clients begtime is 12:30 and endtime is 1400 but clientid=2 (row 9) who begtime =1230 but endtime = 1300. However, since this client begtime is the same as the rest, I wan that client to be in the second group (grp2) My partition over creates 4 groups rather than two.
View 9 Replies
View Related
Nov 3, 2015
I am trying to find a solution to get the result set to fetch a particular string format from a table in my database, which has a column of NVARCHAR data type
CREATE TABLE #ActivityComments(Comments NVARCHAR(MAX))
INSERT INTO #ActivityComments VALUES('This is the study code for Field Phase S14-04932-01')
INSERT INTO #ActivityComments VALUES('Phase reporting has the study S15-04931-01 which is obselete')
INSERT INTO #ActivityComments VALUES('Phase running study code S14-04932-02 is not valid')
The output of the query should be like:
S14-04932-01
S15-04931-01
S14-04932-02
Is there any way possible to achieve this..
View 7 Replies
View Related
Aug 6, 2014
I'm trying to do the following and haven't been able to figure it out.
Say there's a table with these records:
Col1 Col2 Col3
a b c
a b c
a b d
e f g
e f g
I want to generate a number that represents the groups of columns like this:
Col1 Col2 Col3 MyNumber
a b c 1
a b c 1
a b d 2
e f g 3
e f g 3
So that each grouping gets its own identifier. I've tried this:
SELECT Col1, Col2, Col3
row_number() OVER (PARTITION BY Col1, Col2, Col3
ORDER BY Col1, Col2, Col3) AS MyNumber
FROM MyTable
But I get this:
Col1 Col2 Col3 MyNumber
a b c 1
a b c 2
a b d 1
e f g 1
e f g 2
View 9 Replies
View Related
Jan 21, 2014
I have a dataset that contains an EmployeeID, StartDate, EndDate, and Location. Each record tells me at which location and employee was during a payroll period (fortnightly). So the data looks like:
EMP_KEYSTART_DTEND_DTLOCATION
120130117201301318103
120130117201301318103
120130131201302143354
120130131201302148103
220130117201301311234
220130131201302144567
120130214201302283354
220130214201302281234
Employees can be at multiple locations during the two weeks. They can work at one location, stop working there, start working somewhere else, and then maybe go back to their old location. There are duplicate records here as each employee can be at the same location multiple times during the two week period. What I need to capture is the actual start and end date of an employee at each location for each 'assignment'. An assignment is defined as a continual period of employment at a location with gaps of no less than 4 days - if there is a gap of more than four days then that is classed as a new assignment.
View 7 Replies
View Related
Jan 16, 2015
I have some data where a bit value changes over time and I want to rank it by the repeating groups, how do I write the SQL so that I get the result below?
I want to sort by create date, and every time the bit changes value we start the rank over.
If I partition by the bit field, it will just group the entire data set by the bit field.
Bit CreateDate Rank
1 3/15/2014 1
1 3/14/2014 2
0 3/9/2014 1
0 3/8/2014 2
0 3/6/2014 3
1 3/4/2014 1
0 2/28/2014 1
0 2/20/2014 2
0 2/15/2014 3
0 2/10/2014 4
View 3 Replies
View Related
Jul 13, 2007
My query works correctly inside of query analyzer, but in my .aspx page I get the following error message, "The server tag is not well formed."If I remove the parameters then the sqldatasource does not yield errors. The parameters are passed from two textboxes on the page.
Thank You.
AyomideMy sqldatasource is:
<asp:SqlDataSource ID="sqlException"
runat="server" ConnectionString="<%$ ConnectionStrings:AttendanceConnectionString %>"
SelectCommand="SELECT ATTTblAttendance.UserID, ATTTblAttendance.Today, "
"ATTWASDEmployees.LastName, "
"ATTWASDEmployees.AttRowID, ATTWASDEmployees.FirstName, ATTTblAttendance.AMBreakOut, "
"ATTTblAttendance.AMBreakIn, ATTTblAttendance.LunchOut, "
"ATTTblAttendance.PMBreakOut, ATTTblAttendance.PMBreakIn, ATTTblAttendance.Logout, "
"ATTTblAttendance.Login, "
"ATTTblAttendance.LunchIn FROM ATTTblAttendance INNER JOIN "
"ATTWASDEmployees ON ATTTblAttendance.UserID = ATTWASDEmployees.EmployeeID "
"WHERE ((ATTTblAttendance.AMBreakOut IS NULL) OR "
"(ATTTblAttendance.AMBreakIn IS NULL) OR "
"(ATTTblAttendance.LunchOut IS NULL) OR "
"(ATTTblAttendance.PMBreakOut IS NULL) OR "
"(ATTTblAttendance.PMBreakIn IS NULL) OR "
"(ATTTblAttendance.Logout IS NULL)) ""AND (ATTTblAttendance.Today >= @BeginDate and ATTTblAttendance.Today <= @EndDate) "
"ORDER BY ATTTblAttendance.Today, ATTWASDEmployees.LastName, ATTWASDEmployees.FirstName" >
<SelectParameters>
<asp:Parameter Name="BeginDate" Type="string" />
<asp:Parameter Name="EndDate" Type="string" />
</SelectParameters>
</asp:SqlDataSource>
View 2 Replies
View Related
Sep 19, 2014
How Choose function in SQL is useful in a table. Any example with a simple table and how it can be useful for any particular column in a table
View 1 Replies
View Related
Nov 30, 2005
The following SQL works on Access and Oracle to return the number of
Groups(Rows) of the SQL. In MS-SQL this SQL is not valid. What is the
equivalent in MS-SQL?
Select Count(1) FROM (Select ShipRegion, Sum(FREIGHT) as [TotalFreight]
from ORDERS WHERE OrderID < 123456 GROUP BY ShipRegion )
Thanks,
Frankk
View 2 Replies
View Related
Mar 20, 2008
hi,
not sure if the title really expains what I want to achieve...
I have a table which is like :
name groups number
bob 1 160
bob 51 160
bob 101 160
What I need to do is split the 160 into the correct groups..
so the first 50 goes into group 1, then next 50 in group 51, then the next 60 in 101..
so the result would look like :
name groups number
bob 1 50
bob 51 50
bob 101 60
thank you for any advice.
View 7 Replies
View Related
Oct 18, 2007
Counting groups
I have the following code that is grouped by name
Mike G ( from 2000 €“ 2003)
Address Raise
Test 1
Test 1
Mike G ( from 2004 €“ 2007)
Address Raise
Test 2 1
Test 2 1
Mark G ( from 2004 €“ 2007)
Address Raise
Test 2 1
Test 2 1
Total 6 (I get this without any problem)
The problem I am having is trying to find out how many groups we have to use the value for some other calculation. So I did this Count(Field .Name) wich will give me 6 instead of 3 . The reason is in my dataset it will be something like that
Name add raise Period
Mike G Test 1 2000-2003
Mike G Test 1 2000-2003
Mike G Test 1 2004-2004
Mike G Test 1 2004-2007
Mike G Test2 1 2004-2007
Mike G Test2 1 2004-2007
If I do CountDistinct(Field .Name) it will give me 2 which is also wrong . So how can I count many groups we have. I spend a lot of time on this please help!
Thanks
View 9 Replies
View Related
Jul 30, 2007
I am trying to restore a 2005 backup to a 2005 database on another server. This has worked for me before. I have tried to take the backup 5 times now and each time I get the error media family incorrectly formed. Since I have successfully backed up and restored before between these same two databases I do not understand what is wrong now.
I found other questions with this error; however, they were taking a 2000 backup to a 2005 database. I am using a backup of a 2005 database to a 2005 restore.
How should I begin to debug this problem?
Thanks
View 3 Replies
View Related
May 25, 2015
I have a table which has 2 columns and the data is like below
API_Number       Group_Name
1234Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Group A
3241Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Group A
1234Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Group B
4567Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Group C
7896Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Group D
3241Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Group E
 I wanted to find the API numbers which are repeating in different groups. In the output I want
 API_Number          Group_Name
1234Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Group A,Group B
3241Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Group A,Group E
View 5 Replies
View Related
Dec 5, 2013
I am having problems getting my last revision number out when i am trying to use inner joins along with the row_number over partition
I am using 2 tables, tbl_acyear_lookup & tbl_targets
tbl_acyear_lookup columns = (pk)- academic_year_id, academic_year
looks like this:
1, 2010/2011
2, 2011/2012
3, 2012/2013
tbl_targets columns = targetID, Academic_Year_ID,Course_Mode,UK_ENROL, INT_ENROL, Notes, Revision_Number
I have one stored proc that uses the Row_number over partition that looks like this:
Select TargetID, Academic_Year_id, Course_Mode, UK_Enrol, Int_Enrol, Notes, Revision_Number from
(SELECT ROW_NUMBER() OVER (partition by [Academic_Year_id] order by [Revision_Number] DESC) as [RevNum],TargetID, Academic_Year_id, Course_Mode, Target_Year, UK_Enrol, Int_Enrol, Notes, Revision_Number
FROM tbl_targets where course_mode=@course_mode) RV where (RV.RevNum=1)
Now the next store proc needs to use the above but i need to add the Academic_year from the tbl_acyear_lookup table also add filter the target_year ='year 1'
View 2 Replies
View Related
Feb 11, 2014
Trying to find out if this is the best way to move log files in databases that are in an availability group.
remove the DB from the AG
Run alter database commands like you would normally to take offline ,move file,bring online ,etc
drop the db from secondary node
then rejoin the DB to the AG
Is that the only option for moving them when its in an avail group? cant find any other info on moving files in mirrors or HA groups
View 2 Replies
View Related
Jun 30, 2014
I been trying to learn availability groups since I have not implemented it.
From my understanding you can have more than one group.
Lets pretend we have two groups in one instance:
1. Accounting
2. Engineering
From my understanding you can't make a database in two AG because it wouldn't make sense.
But lets pretending there is one database that both are used by accounting and engineering.
Would you have to make a third AG for future fail overs so that other databases in the other two group don't failover when not needed because when you fail over an AG all the databases inside it fail over.
View 3 Replies
View Related
May 13, 2015
So, today we have the following:
Dallas: A 2 node Windows 2008 Cluster running SQL 2012 ENT cluster
Wash: A 2 node Windows 2008 Cluster running SQL 2012 ENT cluster
and I'm mirroring (synchronous, no witness) a database from Dallas to Wash.Crappy set up. I know.Now customer wants to have the database mirror to another server in Dallas.What are the high level steps to transform my two clusters to use Availability Groups and Always On?Do I need to basically start over and build a new environment?or can I transform my two disconnected cluster?
View 4 Replies
View Related
Mar 5, 2015
With this query i get only the records i need, but i would like to output in this way
1 - 20
21 - 30
31 - 40
of course in the real environment the ID are not consecutive, this is just one example of data.
declare @temp table (ID int)
declare @i int = 1
while(@i<1000) begin
insert into @temp values (@i)
set @i=@i+1
end
select ID from (
select ID, row_number() over (order by ID)
as rn
from @temp
) q where (rn % 20=0) OR (rn % 20=1)
View 3 Replies
View Related
Aug 12, 2013
From what I understand, one SQL Server 2012 instance can host multiple availability groups. That should allow, for example, the following situation - one SQL Server 2012 instance containing three primary replica databases - each one part of a different availability group - and each availability group's secondary replica located on a separate SQL Server 2012 instance.
Can you have three SQL Server 2012 instances, each with one primary replica database and have all three secondary replica databases on one SQL Server 2012 instance? So instead of, as above, going from 1 primary server to 3 secondary servers, this time we're going from 3 primary servers to 1 secondary server? The one secondary server would then contain all three secondary replicas for each of the 3 separate primary replicas.
This would mean that the single server (where all three secondary replicas reside) was part of three separate Windows Server Failover Clustering clusters.
Is this scenario possible?
View 4 Replies
View Related
Feb 13, 2014
I have four instances and each instance have its own Availability Group with its own listener.
Would like to know if you can have one listener for multiple Availability groups?
View 2 Replies
View Related
Apr 28, 2014
I am looking for the easiest way of rebalancing data across multiple files.
Instead of creating a secondary filegroup and then dropping and recreating all indexes in the database which is going to take ages (we have a lot of tables and indexes), I am trying to just add more files to the primary file group and then rebalance data evenly between these.
I guessed that adding the new files to the primary file group and then rebuilding all indexes on a table should redistribute the table over these multiple file groups evenly. This is not the case though. It does rebalance data a bit but I still end up with the majority on the first file that existed.
I have attached the script I am running, maybe it is something in the create database/file statements that is the issue.
Basically what I am seeing is to start off with the table is 160MB. I then add the file groups and rebuild all indexes on the table. The first file is then about 100MB and each of the three other files are about 20MB. I would expect them all to be the same size.
View 4 Replies
View Related
Apr 28, 2014
We had 3 Availability Groups set up in SQL 2012 last year but they were poorly named so I am just looking to rename them but there doesn't seem to be any command for it that I can find.Can they not be renamed once created? I guess I could just create new ones and move the DB's into them but just thought I would check!
View 1 Replies
View Related
Jul 30, 2014
We have a large Datawarehouse and the size is 50TB.. The tables are placed in filegroups based on the schema like fact, dimensions, raw data each sit on seperate filegroups. I am thinking will it make sense to seperate the large facts which are having billions of rows so that they reside on filegroups on their own..
View 9 Replies
View Related
Aug 14, 2014
I have several 2012 availability groups running on a cluster. I have one database that is bulk loaded every 30 minutes. The DB is about 1 GB in size. To be on the availability group it has to be set to full recovery mode, but simple or even bulk would obviously be better. Is there a better way to handle the transaction log size other than to run a backup after each bulk load causing extra overhead? With mirrors you could use simple, but since those are going away . . .
View 2 Replies
View Related
Aug 15, 2014
I would like synchronizing all the missing objects (logins, agent jobs, SSIS, and anything else that I've missed) across SQL 2012 Availability Groups.
I would like to be able to able to automate this process....
View 2 Replies
View Related
Mar 20, 2015
We have a sorted data that looks like the first 3 columns below, and fourth colum is what I want to create)
Shift_start meal_break shift_endShift ID
1 0 0 1
0 0 0 1
0 0 1 1
1 0 0 2
0 0 0 2
0 0 1 2
I need to find a method to assign unique Shift IDS to rows that correspond to a single shift. For instance, the first shift would begin on the first row when shift_start flag is turned on, and end on the third row when shift_end flag is turned on.
Can I do this in SQL ?...some kind of grouping ?
View 2 Replies
View Related
Sep 8, 2015
We have some tables that are bulk-loaded every day and they do not have RI to the other tables in the database.
To ease pressure on the logs, I had the idea of spinning them off to another database on the same AG in simple or bulk-load recovery model and using synonyms to point to them so the code base would not need changing.
I know an earlier bug in 2005 existed that basically made the query analyzer ignore indexes if a table was accessed via a synonym.
View 0 Replies
View Related
Sep 15, 2015
We have multiple SQL 2012 SQL servers setup in an alwaysOn availability groups. Where should we schedule the re-index? We have Server1 as the primary and 2 secondaries Server2 and Server3. Are their any tricks to have it run on which ever one is the primary?
View 1 Replies
View Related
Nov 26, 2013
How to create a row number for a consecutive action. Example: I have a listing of people who have either completed a goal or not. I need to count by person the number of consecutively missed goals.
My sql table is this:
PersonId, GoalDate, GoalStatus (holds completed or missed)
My first thought was to use the rownumber function however that doesn’t work because someone could complete a goal, miss a goal, then complete one and when they complete a goal after a missed goal the count has to start over.
View 9 Replies
View Related
Dec 19, 2013
Consider the following data
create table #sampletbl
(
Category varchar(100),
Numbers varchar(100),
Status varchar(100)
)
insert into #sampletbl values ('A','29710000001','0')
[code]....
if status = 0 then unused status = 1 then used
i need to find 10 continues unused numbers
This is the sample data. In live I'm having plenty of data like that . So quite complex.
note : In real world I need to find the 1000 continues number ranges.
View 8 Replies
View Related
May 5, 2015
In a t-sql 2012 select statement, I have a query that looks like the following:
SELECT CAST(ROUND(SUM([ABSCNT]), 1) AS NUMERIC(24,1)) from table1. The field called [ABSCNT] is declared as a double. I would like to know how to return a number like 009.99 from the query. I would basically like to have the following:
1. 2 leading zeroes (basically I want 3 numbers displayed before the decimal point)
2. the number before the decimal point to always display even if the value is 0, and
3. and 2 digits after the decimal point.
View 3 Replies
View Related
Jul 23, 2015
I am trying to calculate the number of hours a device has been used and I cant find how. I need a query that calculated and does an average of the number of hrs used in a week.
View 5 Replies
View Related
Sep 8, 2015
I have the following scenario:
SQL database on SQL 2012
Large Production table 15 Million record
The table has 3 years of data
New monthly data is being added every month.
A New Monthly data is being loaded, checked and finally approved after 6 or 7 iteration before approval.Because of this iteration the monthly data set is being added then deleted then added then deleted few times.Because the table is big this process takes time, any thoughts on how to make the delete insert process faster.Keep in mind I cannot do much because it is a production table and is being access by other users to do other analysis.
Delete is done based on trx_date which is a year/month combo, like 201508.
The table has monthly sales by customer aggregated.
The table structure is:
CREATE TABLE [dbo].[Sales](
[batch_key] [int] NOT NULL,
[Company_key] [int] NOT NULL,
[customer_key] [char](22) NOT NULL,
[Trx_Date] [int] NOT NULL,
[account] [nvarchar](35) NOT NULL,
[code].....
View 9 Replies
View Related