I have a SQL Server table which have records like this
1 | 100
2 | 150
3 | 250
4 | 600
5 | 1550
6 | 50
7 | 300
I need to select random records, but the only condition is that the total sum of this records value achieve a specific number or percentage i define.
1 | 100
2 | 150
6 | 50
3 | 250
6 | 50
7 | 300
can any one help me to do this.
SQL SUM() and COUNT() using variable SUM of values of a field or column of a SQL table, generated using SQL SUM() function can be stored in a variable or temporary column referred as alias. The same approach can be used with SQL COUNT() function too.
On the Home tab, in the Records group, click Totals. A new Total row appears in your datasheet. In the Total row, click the cell in the field that you want to sum, and then select Sum from the list.
Very simply, SUM calculates a total for a number of cells or values, so it's answering the question: HOW MUCH? Or, WHAT IS THE TOTAL? COUNT tells you HOW MANY cells meet a certain condition.
If you need to add a group of numbers in your table you can use the SUM function in SQL. This is the basic syntax: SELECT SUM(column_name) FROM table_name; If you need to arrange the data into groups, then you can use the GROUP BY clause.
Think this recursive CTE works, no idea what the performance will be like though once you get past a trivial amount of rows:
DECLARE @Test TABLE
(
ID INT NOT NULL,
VAL INT NOT NULL
);
INSERT INTO @Test
VALUES (1,100),
(2,150),
(3,250),
(4,600),
(5,1550),
(6,50),
(7,300);
DECLARE @SumValue INT = 300,
@Percentage INT = 10;
WITH GetSums
AS
(
SELECT T.ID,
T.Val,
CAST(T.ID AS VARCHAR(MAX)) AS IDs
FROM @Test AS T
UNION ALL
SELECT T1.ID,
T1.Val + GS.Val AS Val,
CAST(T1.ID AS VARCHAR(MAX)) + ',' + GS.IDs AS IDs
FROM @Test AS T1
INNER
JOIN GetSums AS GS
ON T1.ID > GS.ID
)
SELECT GS.IDs,
GS.Val
FROM GetSums AS GS
WHERE (GS.Val = @SumValue OR GS.VAL = (SELECT SUM(Val) FROM @Test AS T) / @Percentage)
OPTION (MAXRECURSION 50);
Similar found here:
find all combination where Total sum is around a number
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With