how to select all on laravel query builder? - laravel

(1)
DB::query()
->select(*) <----how to write it's error
->addSelect(DB::raw('SUM(CASE WHEN B.approve IS NULL THEN 0 ELSE 1 END) as Ashowcount'))
->addSelect(DB::raw('SUM(B.approve) as Yshow'))
->from(a16 as A)
.....
(2)
DB::table(a16 as A')
->Select(DB::raw('SUM(CASE WHEN B.approve IS NULL THEN 0 ELSE 1 END) as Ashowcount'))
->addSelect(DB::raw('SUM(B.approve) as Yshow'))
...... <---just select two column
I want to ask how can I select all from a16 with above two query code?
I need use addselect to add the DB:raw code
I only can type one by one just like
->select('A.id','A.s_main','A.s_brand','A.s_model','A.s_price','A.s_count','A.s_unit','A.s_location','A.s_geography','A.s_location','A.u_id','A.classify','A.s_boss','A.route','A.created_at')
I feel it's some no efficiency.
How can I select all column easily?

DB::query()
->select('A.*')
->addSelect(DB::raw('SUM(CASE WHEN B.approve IS NULL THEN 0 ELSE 1 END) as Ashowcount'))
->addSelect(DB::raw('SUM(B.approve) as Yshow'))
->from(a16 as A)

Related

Optimize laravel join query

Is there anyone who can optimize below query please. Mids table has records 166 and orders table has records 350000 (0.35 million). Query is taking more than one minute on local as well as in database. Please check below query code:
DB::table('mids')->join('orders', 'orders.gateway_id', '=', 'mids.gateway_id')
->select(DB::raw('mids.*', DB::raw('SUM(orders.order_total) as sum')))
->addSelect(DB::raw('sum(case when orders.order_status = "2" then 1 else 0 end) as mid_count'))
->addSelect(DB::raw('sum(case when orders.order_status = "7" then 1 else 0 end) as decline_per'))
->groupBy('mids.id')->get();
hey brother instead of multiple DB::raw and addselect() you cam simply use it in this way:
DB::table('mids')->join('orders', 'orders.gateway_id', '=', 'mids.gateway_id')
->select(DB::raw('mids.*, SUM(orders.order_total) as sum,
sum(case when orders.order_status = "2" then 1 else 0 end) as mid_count,
sum(case when orders.order_status = "7" then 1 else 0 end) as decline_per'))
->groupBy('mids.id')->get();
But i suggest use pagination if you are fetching large data and for pagination docs will be more helpful: Database: Pagination

Orcale - Missing Right Paranthesis

I am trying to run an oracle query using, Case when and Sum together, It gives me an error saying I am missing the right paranthesis.
The query below,
SELECT c.Customer_name,
CASE WHEN SUM(status = 'DELIVERED') = count(*) THEN 'A'
WHEN SUM(status = 'DELIVERED') > 0 THEN 'B'
WHEN SUM(status = 'SUBMITTED') > 0 THEN 'C'
ELSE 'No Match'
END AS Match
FROM Customer_Order c
group by c.Customer_name order by c.Customer_name;
Changed my query to look like this and it says, I am missing keyword
SELECT c.Customer_name,
CASE WHEN SUM(c.status) = 'DELIVERED' = (count(c.status)) THEN 'A'
WHEN SUM(c.status) = 'DELIVERED' > 0 THEN 'B'
WHEN SUM(c.status) = 'SUBMITTED' > 0 THEN 'C'
ELSE 'No Match'
END AS Match
FROM Customer_Order c
group by c.Customer_name order by c.Customer_name;
Ok, what I think you are trying to do includes counting all the cases where status = 'DELIVERED' and status = 'SUBMITTED' and then comparing those with something to determine what the outcome is. But you can't sum a conditional expression like status = 'DELIVERED' so you need to do it in two steps: one to make a number out of the conditional and one to compare the sum with something.
Step 1: To count the cases where status = 'DELIVERED' you need a column that is 1 when the status is DELIVERED and 0 when it is not (and the same with 'SUBMITTED'). That way you have numbers to sum. So the data we want to run your query on is:
SELECT *,
CASE WHEN status = 'SUBMITTED' THEN 1 ELSE 0 END AS Is_submitted,
CASE WHEN status = 'DELIVERED' THEN 1 ELSE 0 END AS Is_delivered
FROM Customer_order
Step 2: Now we can use your query on the results of Step 1:
SELECT
c.Customer_name,
CASE WHEN SUM(c.delivered) = count(*) THEN 'A'
WHEN SUM(c.delivered) > 0 THEN 'B'
WHEN SUM(c.submitted) > 0 THEN 'C'
ELSE 'No Match'
END AS X
FROM (the query above) as c
GROUP BY c.Customer_name
ORDER BY c.Customer_name;
Substituting Step 1 into Step 2 we get the actual query:
SELECT
c.Customer_name,
-- SUM(c.Is_delivered),
-- SUM(c.Is_submitted),
-- count(*),
CASE WHEN SUM(c.delivered) = count(*) THEN 'A'
WHEN SUM(c.delivered) > 0 THEN 'B'
WHEN SUM(c.submitted) > 0 THEN 'C'
ELSE 'No Match'
END AS X
FROM (
SELECT *,
CASE WHEN status = 'SUBMITTED' THEN 1 ELSE 0 END AS submitted,
CASE WHEN status = 'DELIVERED' THEN 1 ELSE 0 END AS delivered
FROM Customer_order
) as c
GROUP BY c.Customer_name
ORDER BY c.Customer_name;
Try it here:
https://www.db-fiddle.com/f/mSdREEgU1mT1pvczG2kZgm/1
You appear to be trying to count true comparions; unlike some other languages, in SQL a true value is not the same as 1 and a false value is not 0 so you need to use a CASE expression to convert the comparison to something that can be summed (or counted).
In this case, you can use conditional aggregation:
SELECT Customer_name,
CASE
WHEN COUNT(CASE status WHEN 'DELIVERED' THEN 1 END) = COUNT(status)
THEN 'A'
WHEN COUNT(CASE status WHEN 'DELIVERED' THEN 1 END) > 0
THEN 'B'
WHEN COUNT(CASE status WHEN 'SUBMITTED' THEN 1 END) > 0
THEN 'C'
ELSE 'No Match'
END AS Match
FROM Customer_Order
group by Customer_name
order by Customer_name;

postgres inner join sum for when no relation exists

I am trying to run a simple query where I get a sum of gardeners who have zero support visits. I would like to add other cases, but first I would like to get this zero thing right. This is what I have come up with:
Gardener.from(Gardener.joins(:support_visits).group(:gardener_id).select("CASE WHEN count(gardener_id) = 0 THEN 1 END AS zero_count"),:t).select("sum(t.zero_count) as tot_zero_count")
Which gives me the following sql query:
SELECT sum(t.zero_count) as tot_zero_count
FROM
(
SELECT CASE WHEN count(gardener_id) = 0 THEN 1 END AS zero_count
FROM "gardeners" INNER JOIN "support_visits"
ON "support_visits"."gardener_id" = "gardeners"."id"
GROUP BY gardener_id
) t
The query runs but gives me nil.
Your current query uses count(gardener_id) = 0 which is never true because any group will have at least one record. Instead, you can LEFT JOIN the gardeners table to the support_visits table. Any gardener which does not appear in the support_visits table will not match to a visit, leaving a null value which you can then count.
SELECT SUM(CASE WHEN "support_visits"."gardener_id" IS NULL THEN 1 ELSE 0 END) AS zero_count
FROM "gardeners" LEFT JOIN "support_visits"
ON "support_visits"."gardener_id" = "gardeners"."id"
Here is the Ruby ActiveRecord code for this query:
Gardener.from(Gardener.joins("LEFT JOIN `support_visits` ON gardeners.id = support_visits.gardener_id").select("SUM(CASE WHEN "support_visits"."gardener_id" IS NULL THEN 1 ELSE 0 END) AS zero_count"))

Aggregated column use in Hive Query

My hive table (tab1) structure:
people_id,time_spent,group_type
1,234,a
2,540,b
1,332,a
2,112,b
Below is the query i am trying to execute but getting error ("Not yet supported place for UDAF 'sum'"):
select people_id, sum(case when group_type='a' then time_spent else 0 end) as a_time, sum(pow(a_time,2)) as s_sq_a_time,sum(case when group_type='b' then time_spent else 0 end) as b_time, sum(pow(b_time,2)) as s_sq_b_time from tab1 group by people_id;
Is it possible to refer aggregated column from same select statement in Hive?
I have also referred below link but it didnt work:
http://grokbase.com/t/hive/user/095tpdkrgz/built-in-aggregate-function-standard-deviation#
Set an alias for the table name and use the table alias when accessing the columns.
E.g.
select startstation, count(tripid) as a
from 201508_trip_data as t
group by t.startstation
Note 't' is the alias for the table and I've used t.startstation to access the
You'll have to use a derived table to refer to a_time and b_time
select a_time, b_time,
pow(a_time,2) as s_sq_a_time,
pow(b_time,2) as s_sq_b_time
from (
select people_id,
sum(case when group_type='a' then time_spent else 0 end) as a_time,
sum(case when group_type='b' then time_spent else 0 end) as b_time
from tab1 group by people_id
) t1

Using Linq (nHibernate) to perform a Case statement with Counts

I'm sure this is one has done the houses a few times but i've never found a solution...
So is it possible to do something like this using nHibernate 3 with preferably Linq:
SELECT
COUNT(CASE WHEN IsWithdrawn = 1 THEN 1 END) AS WithdrawnCount,
COUNT(CASE WHEN IsWithdrawn = 0 THEN 1 END) AS ViewAllCount
FROM Tutorials
I'm pretty sure that is isn't possible and that the best solution is to opt just for sql in this case... but maybe there is something new in nHibernate 3.1 that can do this with, even using queryover?
thanks
You can do it with HQL, which is almost the same as SQL:
SELECT
SUM(CASE WHEN IsWithdrawn = 1 THEN 1 ELSE 0 END) AS WithdrawnCount,
SUM(CASE WHEN IsWithdrawn = 0 THEN 1 ELSE 0 END) AS ViewAllCount
FROM Tutorials
(I'm not sure if the COUNT would work, I'm sure SUM does)
Here's a LINQ version that should work too:
session.Query<Tutorial>()
.GroupBy(x => x.IsWithdrawn)
.Select(x => new { x.Key, Count = x.Count() })
You can use Projections.Conditional with Criteria or QueryOver, but it's more work.
You can get the desired result with QueryOver, although it will be slower due to the subqueries.
var sums = repo.Session.QueryOver<Tutorials>()
.SelectList(list => list
.SelectSubQuery<Tutorials>(NHibernate.Criterion.QueryOver.Of<Tutorials>()
.Where(t => t.IsWithdrawn)
.ToRowCountQuery())
.SelectSubQuery<Tutorials>(NHibernate.Criterion.QueryOver.Of<Tutorials>()
.ToRowCountQuery())
)
.Take(1) // we want only one row in our result. In SQL I would use " from dummy".
.List<object[]>();
Explanation:
I use two detached QueryOvers. The first one counts the rows in Tutorials where IsWithdrawn = true, the second once counts all rows. The two detached QueryOvers are then used as SubQueries in a normal QueryOver with a Projection (SelectList).
Here is the generated SQL:
SELECT TOP (1)
(SELECT count(*) as y0_ FROM [Tutorials] this_0_
WHERE this_0_.IsWithdrawn = True) as y0_,
(SELECT count(*) as y0_ FROM [Tutorials] this_0_) as y1_
FROM [Tutorials] this_;

Resources