1

Want to select 3 item with values by random and show its total at the end

Example:

A  diner 2
B  lunch 3
C  diner 4
D  lunch 5 

I want result for diner like:

A 2
C 4
Total 6
forpas
  • 160,666
  • 10
  • 38
  • 76

2 Answers2

0

You can try the following:

STRING QUERY = SELECT SUM(COLUMN_NAME_QUANTITY) FROM TABLENAME WHERE COLUMN_NAME_TIME_OF_MEAL = "diner"

After executing this query, it should return the total for diner.

iamdanchiv
  • 4,052
  • 4
  • 37
  • 42
Salman
  • 9
  • 4
0

This is quite tricky because it involves persisting the random rows to perform aggregation.
So I use a CTE that returns the random rows along with a dummy row containing the string 'Total' and a value of 0 for Col3.
Finally with CASE the code returns either Col3, if the row is one of the random rows or the sum of all the values in Col3 if the row is the Total row:

with cte as ( 
  select * from (
    select 0 sortorder, col1, col3
    from tablename
    where col2 = 'diner'
    order by random()
    limit 2
  )  
  union all
  select 1, 'Total', 0
)
select col1,
  case
    when sortorder = 0 then col3
    else sum(col3) over()
  end Total
from cte
order by sortorder 

See the demo (I added more rows to your sample data).

forpas
  • 160,666
  • 10
  • 38
  • 76