sql server - Return a column to notify row change of another column -


i have table:

|----fruit----| |-------------| |--apples--| |--apples--| |--apples--| |--apples--| |-bananas-| |-bananas-| |-oranges-| |--plums---| |--plums---| 

i have below script:

case when [fruit] = [fruit] '0' else [fruit] end 

what want return 2 columns. 1 fruit column , 2nd column shows when fruit column changes next fruit, have following:-

|----fruit----||fruit change| |-------------||----------------| |--apples--||-------0-------| |--apples--||-------0-------| |--apples--||-------0-------| |--apples--||-------0-------| |-bananas-||--bananas--| |-bananas-||-------0-------| |-oranges-||---oranges---| |--plums---||----plums----| |--plums---||-------0-------| |--plums---||-------0-------| |--plums---||-------0-------| |--plums---||-------0-------| |--mango---||---mango---| |--mango---||-------0-------| 

how return column corresponding change in fruit script above doesn't allow me specify need do.

you can use lag below:

select fruit,case when fruit <> lag(fruit) over(order id) fruit else '0' end fruitchange      #data 

output below:

+---------+-------------+ |  fruit  | fruitchange | +---------+-------------+ | apples  | 0           | | apples  | 0           | | apples  | 0           | | apples  | 0           | | bananas | bananas     | | bananas | 0           | | oranges | oranges     | | plums   | plums       | | plums   | 0           | +---------+-------------+ 

Comments

Popular posts from this blog

networking - Vagrant-provisioned VirtualBox VM is not reachable from Ubuntu host -

c# - ASP.NET Core - There is already an object named 'AspNetRoles' in the database -

ruby on rails - ArgumentError: Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true -