0

I'm trying to select multiple database columns and to merge them to an AS value statement like SELECT sum1 as vsd FROM tablename WHERE year = 2017

I have multiple columns I need to output as one value. So I imagine the above code looking something like this:

SELECT (sum1, sum2) as vsd FROM tablename WHERE year = 2017

My current live-code query looks like this:

$query = DB::table('exports')->select('id', 'year', 'week', 'month', 'staff_a, staff_b as vsd')->having('year','=',$year)->where('week', '<=', $weeknr)->orderBy('id', 'desc')->take(14)->get()->reverse();

The result is:

Column not found: 1054 Unknown column 'staff_a, staff_b' in 'field list'

I tried to combine them (columns) to an array (array('staff_a', 'staff_b')), had some weird foreach-loops and whatnot trying to make it work another way but all that threw yet another error message.

Is there any way to "merge" multiple selects to one?

2
  • (sum1, sum2) as vsd this is not merging even in mysql. How do you want to merge them ? by adding both columns sum1 + sum2 as vsd? Commented Oct 24, 2017 at 18:06
  • @MKhalidJunaid Yes, they should be added together, simple math if you will. Commented Oct 24, 2017 at 18:29

1 Answer 1

2

You have to use RAW syntax:

->select(DB::raw('staff_a + staff_b as vsd'))

Ref: https://laravel.com/docs/5.5/queries#raw-expressions

Sign up to request clarification or add additional context in comments.

3 Comments

Unfortunately, that only uses the last column (staff_b) as vsd and outputs the first column as staff_a.
@Andreas see the update one this should do what you want
@MKhalidJunaid That did it. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.