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 |
|
funk.phenomena
Posting Yak Master
121 Posts |
Posted - 2011-07-22 : 17:08:58
|
| Hi All - I have the following table:RECORDID----TELNUM1234 41655512341235 41655512341236 41655512341237 41655599881238 41655599881239 41655599881240 4165554444I am trying to write a query that calculates a $6.50 credit only for only first (and second) instances of each telephone number. The output would be as follows:RECORDID || TELNUM || SPIFF1234 4165551234 $6.501235 4165551234 $6.501236 41655512341237 4165559988 $6.501238 4165559988 $6.501239 41655599881240 4165554444 $6.50SELECT RECORDID, TELNUM, 6.5 AS 'SPIFF'FROM ORDERSHow can I modify my query to accomodate this?Thanks! |
|
|
pduffin
Yak Posting Veteran
68 Posts |
Posted - 2011-07-22 : 18:07:40
|
| Weird way but it works.--copy from your table to a temp table as create new field in table --for credit and order by telnumselect recordid,telnum,cast(0.00 as decimal(10,2)) as Spiffinto #YOURTEMPTABLEfrom #YOURTABLEorder by telnumdeclare @telnum bigintset @telnum = 0declare @pos intset @pos = 1-- updates your temp table if first 2 orders for customerupdate #YOURTEMPTABLEset @pos = case when @telnum = telnum then @pos + 1 else 1 end, @telnum = telnum,Spiff = case when @pos < 3 then 6.5 else 0 endselect *from #YOURTEMPTABLE |
 |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2011-07-23 : 04:02:00
|
| [code]update tset t.SPIFF=$6.50from(select SPIFF,ROW_NUMBER() OVER (PARTITION BY TELNUM ORDER BY RECID) AS rnFROM Table)tWHERE rn <=2[/code]------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/ |
 |
|
|
|
|
|