Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
mystifier
Starting Member
12 Posts |
Posted - 2012-06-17 : 08:48:20
|
| Table1 Data: ID,kpi1,kpi2,kpi3,kpi4,kpi5100,4,3,4,2,5101,3,3,5,2,3102,4,2,4,5,1...Query (to find lowest kpi score):select ID, min(score) as Lowest from Table1 UNPIVOT (score for Col in (kpiid1,kpiid2,kpiid3,kpiid4,kpiid5)) as u group by IDReturns:ID,Lowest100,2101,2102,1...I want to add a 'LowestScore' calculated column but I can't figure out what needs to be there.Many thanks. |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2012-06-17 : 11:10:12
|
do you mean this?select t1.*,t2.Lowest from Table1 t1inner join(select ID, min(score) as Lowest from Table1 UNPIVOT (score for Col in (kpiid1,kpiid2,kpiid3,kpiid4,kpiid5)) as u group by ID)t2ON t2.ID = t1.ID ------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/ |
 |
|
|
mystifier
Starting Member
12 Posts |
Posted - 2012-06-17 : 11:31:23
|
| Hi Visakh16,Yes, this is the query I have which works fine, but I wanted to simplify other queries by have a computed column 'Lowest' that has a single row value.I can't get the actual formula right. |
 |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2012-06-17 : 11:40:05
|
wrap the logic in a udf and use it in computed column formulalikeCREATE FUNCTION GetLowestKPI(@ID int)RETURNS intASBEGINDECLARE @MinKPI intselect @MinKPI= min(score) from (SELECT * FROM Table1 WHERE ID = @ID) tUNPIVOT (score for Col in (kpiid1,kpiid2,kpiid3,kpiid4,kpiid5)) as u group by IDRETURN (@MinKPI)ENDthen create the computed column asALTER TABLE Table1 ADD Lowest AS dbo.GetLowestKPI(ID) ------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/ |
 |
|
|
mystifier
Starting Member
12 Posts |
Posted - 2012-06-17 : 14:17:48
|
| Thanks visakh16,That is running now. |
 |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2012-06-17 : 15:03:00
|
| wc------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/ |
 |
|
|
|
|
|
|
|