how to group by with a sql that has multiple subqueries - mysql

I am trying to add a group by SC_FRAMES.GROUPPRODUCTTYPE to this statement:
SELECT
SC_JOBS.CREATIONDATE,
(SELECT SUM(SC_JOBS.GROSSEXCLVAT) FROM SC_JOBS WHERE SC_FRAMES.GROUPPRODUCTTYPE = 'ABC' AND SC_FRAMES.JOBID = SC_JOBS.JOBSID AND SC_JOBS.INVOICEDATE < '1990-01-01') AS Product1,
(SELECT SUM(SC_JOBS.GROSSEXCLVAT) FROM SC_JOBS WHERE SC_FRAMES.GROUPPRODUCTTYPE = 'XYZ' AND SC_FRAMES.JOBID = SC_JOBS.JOBSID AND SC_JOBS.INVOICEDATE < '1990-01-01') AS Product2
FROM
SC_JOBS
INNER JOIN
SC_FRAMES ON SC_FRAMES.JOBID = SC_JOBS.JOBSID
WHERE
SC_JOBS.CREATIONDATE BETWEEN :StartDate AND :EndDate
ORDER BY
SC_JOBS.CREATIONDATE
Any suggestions please?

I think you want a query like this:
SELECT f.GROUPPRODUCTTYPE,
MIN(j.CREATIONDATE),
SUM(case when j.INVOICEDATE < '1990-01-01' then j.GROSSEXCLVAT else 0
end) as Product1
FROM SC_JOBS INNER j JOIN
SC_FRAMES f
ON f.JOBID = j.JOBSID
WHERE j.CREATIONDATE BETWEEN :StartDate AND :EndDate
GROUP BY f.GROUPPRODUCTTYPE
ORDER BY min(j.CREATIONDATE);
It replaces the subqueries with conditional aggregation, based on the invoice date.

Try this:
SELECT
SC_JOBS.CREATIONDATE,
(SELECT SUM(SC_JOBS.GROSSEXCLVAT) FROM SC_JOBS WHERE SC_FRAMES.GROUPPRODUCTTYPE = 'ATI' AND SC_FRAMES.JOBID = SC_JOBS.JOBSID AND SC_JOBS.INVOICEDATE < '1990-01-01') AS Product 1,
(SELECT SUM(SC_JOBS.GROSSEXCLVAT) FROM SC_JOBS WHERE SC_FRAMES.GROUPPRODUCTTYPE = 'ATI' AND SC_FRAMES.JOBID = SC_JOBS.JOBSID AND SC_JOBS.INVOICEDATE < '1990-01-01') AS Product 2
FROM
SC_JOBS
INNER JOIN
SC_FRAMES ON SC_FRAMES.JOBID = SC_JOBS.JOBSID
WHERE
SC_JOBS.CREATIONDATE BETWEEN :StartDate AND :EndDate
GROUP BY
SC_FRAMES.GROUPPRODUCTTYPE
ORDER BY
SC_JOBS.CREATIONDATE

Add GROUP BY SC_FRAMES.GROUPPRODUCTTYPE after the end of your WHERE statement and before your ORDER BY statement. Also change your AS values to not include spaces as I've encountered ploblems with this in the past, so use Product1 as opposed to Product 1

Related

Generate two SUM value columns for two different dates separately in one query

I am trying to combine two queries
select s.id , sum(h.val) as [VAL]
from identity s inner join price_net h on s.date = h.date and s.num_id = h.num_id and s.rec_type = h.rec_type
where s.date = '10/25/21'
and s.rec_type = 'D'
and s.tier = 'P'
group by s.
.
select s.id , sum(h.val) as [VAL]
from identity s inner join price_net h on s.date = h.date and s.num_id = h.num_id and s.rec_type = h.rec_type
where s.date = '10/26/21'
and s.rec_type = 'D'
and s.tier = 'P'
group by s.
and I want it so there is one table with one column for s.id and the next columns are VAL columns for each respective date. Where a value is not available for a give s.id on a specific date it should show NA.
I supppose you are looking for conditional aggregation (CASE WHEN inside the aggregation function).
select
i.id,
sum(case when i.date = date '2021-10-25' then pn.val end) as val_20211025,
sum(case when i.date = date '2021-10-26' then pn.val end) as val_20211026
from identity i
join price_net pn on pn.date = i.date
and pn.num_id = i.num_id
and pn.rec_type = i.rec_type
where i.tier = 'P'
and i.rec_type = 'D'
and i.date in (date '2021-10-25', date '2021-10-26')
group by i.id
order by i.id;
you can use case when for both criteria
select s.id , sum(CASE WHEN s.date = '10/25/21' THEN h.val eLSE O END) as [VAL]
, sum(CASE WHEN s.date = '10/26/21' THEN h.val eLSE O END) as [VAL2]
from identity s inner join price_net h on s.date = h.date and s.num_id = h.num_id and s.rec_type = h.rec_type
where
as.rec_type = 'D'
and s.tier = 'P'
group by s.ìd

Need help converting sql query into laravel query

I need the following sql query into laravel query or how can I run into laravel as it is. thanks
SELECT t.*
FROM (SELECT client_id,product_name, max(real_date) AS max_date
FROM api_hilbertis.transactions
WHERE active = 1 AND real_date <= '2019-03-01'
GROUP BY client_id, product_name) AS m
INNER JOIN api_hilbertis.transactions AS t
ON t.client_id = m.client_id
AND t.product_name = m.product_name
AND t.real_date = m.max_date
AND active = 1
ORDER BY real_date DESC;
You can use laravel raw queries.
Example HERE
So for your case it we could write something like:
$results = DB::select( DB::raw("
SELECT t.*
FROM (SELECT client_id,product_name, max(real_date) AS max_date
FROM api_hilbertis.transactions
WHERE active = 1 AND real_date <= '2019-03-01'
GROUP BY client_id, product_name) AS m
INNER JOIN api_hilbertis.transactions AS t
ON t.client_id = m.client_id
AND t.product_name = m.product_name
AND t.real_date = m.max_date
AND active = 1
ORDER BY real_date DESC"
));
EDIT: example with variables:
$someVariable = $request->input('some_variable');
$results = DB::select( DB::raw("SELECT * FROM some_table WHERE some_col = :somevariable"),
['somevariable' => $someVariable,]
);

Query optimization needed because of too many sub queries and sub query dependency in where conditions

I'm writing code for the production report.
I had written this query
SELECT
P.*,
(
SELECT
COUNT(id) AS cnt
FROM
bales
WHERE
create_date < '2019-11-01' AND product_id = P.id AND(TYPE = 'bale' OR TYPE = 'bag')
) AS before_prod,
(
SELECT
COUNT(id) AS cnt
FROM
bales
WHERE
(
dispatched = '0' OR disp_bunch = '0'
) AND dispatch_date < '2019-11-01' AND product_id = P.id AND(TYPE = 'bale' OR TYPE = 'bag')
) AS before_dispatched,
(
SELECT
COUNT(id) AS cnt
FROM
bales
WHERE
create_date BETWEEN '2019-11-01' AND '2019-11-06' AND product_id = P.id AND(TYPE = 'bale' OR TYPE = 'bag')
) AS production,
(
SELECT
COUNT(id) AS cnt
FROM
bales
WHERE
(
dispatched = '0' OR disp_bunch = '0'
) AND dispatch_date BETWEEN '2019-11-01' AND '2019-11-06' AND product_id = P.id AND(TYPE = 'bale' OR TYPE = 'bag')
) AS production_dispatched,
C.name AS category_name
FROM
products P
INNER JOIN category C ON
C.id = P.category
This query is working but as I have too many records in all tables it takes too much time.
also, I need only records where before_prod, before_dispatched, production, production_dispatched all these subquery results should be greater than 0.
I tried to use having clause but it also takes too much time.
I have also tried php for loop, * LOGIC: first all products than in for loop its production. but it was much slower.*
How can I optimize my query?
You can use join instead and select case to sum your data that matches your conditions.
select p.*, t.*
from products p
inner join (
select t2.id, sum(case when create_date < '2019-11-01' then 1 else 0 end) as before_prod
, sum(case when (dispatched = '0' or disp_bunch = '0') and create_date < '2019-11-01' then 1 else 0 end) as before_dispatched
, sum(case when create_date between '2019-11-01' and '2019-11-06' then 1 else 0 end) as production
, sum(case when (dispatched = '0' or disp_bunch = '0') and create_date between '2019-11-01' and '2019-11-06' then 1 else 0 end) as production_dispatched
from bales t1
inner join product t2 on t2.id= t1.product_id
inner join category t3 on t3.id = t2.category
where t1.TYPE in ('bale', 'bag')
group by t2.id) t
on t.id = p.id

Return count 0 with mysql group by and where by date

I want to create a single query to result data like this:
but when I insert where clause, column name just result a few value from column m_ccode:
Q: how keep all name column values if I insert where clause?
Here the working fiddle:
http://sqlfiddle.com/#!9/687776/10
use MONTH(t.date) = '10' AND YEAR(t.date) = '2018' condition in on cluase like below
demo
SELECT ccode.name,IFNULL(count(DISTINCT u.username),0) as total_active
,(count(DISTINCT u.username) - count(DISTINCT t.username)) as total_non_active
from m_ccode as ccode
left join m_user as u on u.ccode = ccode.id
left join t_safety_act t on t.username = u.username
and MONTH(t.date) = '10' AND YEAR(t.date) = '2018' group by ccode.id;

How to create multiple counts in a mysql statement

I have some trouble to count more than 2 counts in mysql statement.
My count(b.entry_id) as totalbooking wont work. What have i done wrong? Is the statement setup also correctly made​​?
This is how i tried:
"SELECT
t.restaurant_id as restaurant_id, ct.title as title,
count(DISTINCT t.cardid) as totalmembers,
count(t.restaurant_id) as totaltransactions,
count(b.entry_id) as totalbooking
from transactions as t
inner join exp_menucard_booking as b on (t.restaurant_id = b.entry_id)
inner join exp_channel_titles as ct on (t.restaurant_id = ct.entry_id)
inner JOIN exp_channel_data as cd on (ct.entry_id = cd.entry_id)
where t.cardid != 88888888 and ct.status = 'open'
group by t.restaurant_id
order by ct.title asc";
Use this pattern to count subsets of the total rowset:
sum( case when ColumnToBeTested = trueCondition then 1 else 0 end) as SubCount