How to get total count from more table? - mysql

I want to combine three reports. I want to take count in each tables (smr_trn_tsalesenquiry, smr_trn_treceivequotation, smr_trn_tsalesorder), total count from three tables and using where condition employee_gid from hrm_mst_temployee, group by all primary key from above three tables.
select count(*),
(
select count(x.enquiry_gid)
from smr_trn_tsalesenquiry x
where x.created_by=a.employee_gid
) as enquiry_count,
(
select count(y.quotation_gid)
from smr_trn_treceivequotation y
where y.created_by=a.employee_gid
) as quotation_count,
(
select count(z.salesorder_gid)
from smr_trn_tsalesorder z
where z.created_by=a.employee_gid and z.salesorder_status not in('SO Amended','Cancelled','Rejected')
) as sales_count
from hrm_mst_temployee a
group by a.employee_gid;

You can do this by creating scalar Function by passing employee_id and
return the grouped count from it.
This link will help you to understand how to work with functions

Related

MYSQL pivot table dates as rows

I have a table with 3 columns. First column is an identifier, 2nd is value, 3rd is date. Each date has values for many identifiers. I would like to pivot this table in such a way that I have a row for each date and each column has an identifier.
Every answer I find uses CASE to pivot, however in my case I have many (50+) identifiers, and they would change as time goes on.
Here is the code I used, which did not work
with prep as (
select concat(ticker,' ',date) as papel , (pu+pu_juros) as PU, date from table where date >='2021-12-31' and ticker_bench = 'ticker')
select * from prep
pivot (avg(PU) for papel in (select distinct papel from prep))
I tried a second version, defining a table with the values in which to pivot, this also did not work.
with prep_papel as (
select distinct concat(ticker,' ',date) as papel from table where date>='2021-12-31' and ticker_bench = 'ticker'
)
select * from (
select concat(ticker,' ',date) as papel , (pu+pu_juros) as PU, date from table where date >='2021-12-31' and ticker_bench = 'ticker')
as P
pivot (sum(p.PU) for papel in (select * from prep_papel) ) as pv1
Thank you

How to assign a new column name to the sum of columns aggregated in a mysql query

I need to assign a name to the sum of columns aggregated in a mysql query.
This is what is tried:
SELECT
JSON_LENGTH(comments) as c_total,
JSON_LENGTH(likes) as l_total,
(c_total+l_total) as total
FROM posts
Comments and likes columns holds data in json data type.
JSON_LENGTH returns the length of the array.
How can ı get the total value in above example ?
You can reference select fields if they're in subqueries:
SELECT c_total + l_total AS Total
FROM (
SELECT
JSON_LENGTH(comments) as c_total,
JSON_LENGTH(likes) as l_total,
(c_total+l_total) as total
FROM posts
) A
;
otherwise I think you have to repeat the logic:
SELECT
JSON_LENGTH(comments) as c_total,
JSON_LENGTH(likes) as l_total,
(JSON_LENGTH(comments) + JSON_LENGTH(likes)) as total
FROM posts
;

Get Seperate Total of Two MySQL table

I have two table called questions and entries. I want get separate total of both table using one query. Like questions 10 and entries 20. I have tried like below but its giving me two row as totalEntries
SELECT COUNT(*) as totalEntries FROM quiz_entries UNION SELECT COUNT(*) as totalQuestions FROM quiz_questions
Let me know if any one can help me for get seperate result for both table like totalEntries 20 and totalQuestions 10.
Thanks!
Use each query as an expression that returns the number of rows in each table in a SELECT statement:
SELECT
(SELECT COUNT(*) FROM quiz_entries) as totalEntries,
(SELECT COUNT(*) FROM quiz_questions) as totalQuestions
You can do by this also. Because temp table solves our complex problem too.
IF(OBJECT_ID('tempdb..#tblEntries')) IS NOT NULL
DROP TABLE #tblEntries
IF(OBJECT_ID('tempdb..#tblQuestions')) IS NOT NULL
DROP TABLE #tblQuestions
DECLARE #quizEntriesCount INT
DECLARE #quizQuestionsCount INT
SET #quizEntriesCount = (SELECT COUNT(1) FROM quiz_entries)
SET #quizQuestionsCount =(SELECT COUNT(1) FROM quiz_questions)
SELECT #quizEntriesCount AS quizEntriesCount, #quizQuestionsCount AS quizQuestionCount,

MySQL SELECT query that counts left joined rows takes too long

Does anyone know how to optimize this query?
SELECT planbook.*,
COUNT(pb_unit_id) AS total_units,
COUNT(pb_lsn_id) AS total_lessons
FROM planbook
LEFT JOIN planbook_unit ON pb_unit_pb_id = pb_id
LEFT JOIN planbook_lesson ON pb_lsn_pb_id = pb_id
WHERE pb_site_id = 1
GROUP BY pb_id
The slow part is getting the total number of matching units and lessons. I have indexes on the following fields (and others):
planbook.pb_id
planbook_unit.pb_unit_pb_id
planbook_lesson.pb_lsn_pb_id
My only objective is to get the total number of matching units and lessons along with the details of each planbook row.
However, this query is taking around 35 seconds. I have 1625 records in planbook, 13,693 records in planbook_unit, and 122,950 records in planbook_lesson.
Any suggestions?
Edit: Explain Results
SELECT planbook.*,
( SELECT COUNT(*) FROM planbook_unit
WHERE pb_unit_pb_id = planbook.pb_id ) AS total_units,
( SELECT COUNT(*) FROM planbook_lesson
WHERE pb_lsn_pb_id = planbook.pb_id ) AS total_lessons
FROM planbook
WHERE pb_site_id = 1
planbook: INDEX(pb_site_id)
planbook_unit: INDEX(pb_unit_pb_id)
planbook_lesson: INDEX(pb_lsn_pb_id)
Looking to your query
You should add and index for
table planbook column pb_site_id
and eventually a composite one for
table planbook column (pb_site_id, pd_id)

Not getting count of different string - MySql

I have one query as given below,
select device_id,CAST(device_dtt_st as date),count(*) as g,'' as s,'' as m
from event_data_170309
where device_id ='8D-15-DB'and raw_data like %GPRS%'
group by CAST(device_dtt_st as date)
union
select device_id,CAST(device_dtt_st as date),'' as g,count(*) as s,'' as m
from event_data_170309
where device_id ='8D-15-DB' and raw_data like '%SMS%'
group by CAST(device_dtt_st as date)
union
select device_id,CAST(device_dtt_st as date),'' as g,'' as s,count(*) as m
from event_data_170309
where device_id ='8D-15-DB'and !(raw_data like '%SMS%' or raw_data like '%GPRS%')
group by CAST(device_dtt_st as date);
and I got output as in two different row, but I want count in only one row.
see the below scenario,
Union will return multiple rows only.
You will need to wrap all these queries with another query and then count it.
ex.
select count(param), sum(param), param
from
(
select param as param, count(param)
union
another query with same column output
union
yet another query with same column output
) as childQuery
group by childQuery.param
EDIT
Added a aggregated function, whichever you want to use.
EDIT2
SELECT
DEVICE_ID,
DATE,
SUM(IF(DATA LIKE %SMS%,1,0)) AS TOTAL_SMS,
SUM(IF(DATA LIKE %GPRS%,1,0)) AS TOTAL_GPRS,
SUM(IF(DATA NOT LIKE %GPRS% AND DATA NOT LIKE %SMS%,1,0)) AS TOTAL_OTHER,
FROM
YOUR_TABLE T
GROUP BY
T.DATE
ABove query will work for your desired output