SQL Server random sum

Source: Internet
Author: User
Tags id3

Requirement: three data entries in the table are randomly selected. The value of the price field in the three data entries must be between and.

  Create     Database  Db_test
Go
Use Db_test
Go
Create Table Tb_test
(
[ ID ] Int Identity ( 1 , 1 ),
[ Price ] Decimal ( 10 , 2 )
)
Go
Insert Into Tb_test Values ( 200 )
Insert Into Tb_test Values ( 300 )
Insert Into Tb_test Values ( 400 )
Insert Into Tb_test Values ( 500 )
Insert Into Tb_test Values ( 600 )
Insert Into Tb_test Values ( 700 )
Insert Into Tb_test Values ( 800 )
Insert Into Tb_test Values ( 80 )
Insert Into Tb_test Values ( 10 )
Insert Into Tb_test Values ( 20 )
Insert Into Tb_test Values ( 50 )
Insert Into Tb_test Values ( 90 )
Insert Into Tb_test Values ( 30 )
Insert Into Tb_test Values ( 40 )
Insert Into Tb_test Values ( 60 )
Insert Into Tb_test Values ( 70 )
Insert Into Tb_test Values ( 100 )
Insert Into Tb_test Values ( 330 )
Insert Into Tb_test Values ( 520 )
Insert Into Tb_test Values ( 180 )
Go

Select * From Tb_test Where Exists
(
Select * From
(
Select Top 1 Id1, Id2, ID3 From
(
Select A. ID As Id1, B. ID As Id2, C. ID As ID3
From Tb_test A, tb_test B, tb_test C
Where A. ID < B. ID And B. ID < C. ID
And (A. Price + B. Price + C. Price) > = 600
And (A. Price + B. Price + C. Price) <= 700
) T Order By Newid ()
) J
Where Tb_test.id = J. id1 Or Tb_test.id = J. Id2 Or Tb_test.id = J. ID3
)

If you have any questions or errors, you are welcome to correct and discuss them.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.