How to merge the result of two select mysql query [duplicate] - mysql

This question already has answers here:
How can I get multiple counts with one SQL query?
(12 answers)
Closed 1 year ago.
my first query is
select GEAR,count(GEAR)
from new_failure
where STN_CODE = "BVH" group by(Gear);
and its result is
result if image is not visible
# GEAR Total
SIGNAL 8
POINT 16
HASSDAC 5
,SIGNAL 1
SSDAC 1
TRACK CIRCUIT 9
UFSBI 2
DC 1
2nd query
select GEAR,count(GEAR)
from new_failure
where STN_CODE = "BVH"
and MONTH(fail_time) = 4
group by(Gear);
result
# GEAR April
SIGNAL 3
POINT 4
HASSDAC 1
,SIGNAL 1
SSDAC 1
i want result in the form given in image below

You can use either LEFT JOIN, RIGHT JOIN or JOIN depending on what you are aiming to get,
SELECT *
FROM ( select GEAR,count(GEAR)
from new_failure
where STN_CODE = "BVH" group by(Gear) AS A
JOIN ( select GEAR,count(GEAR)
from new_failure
where STN_CODE = "BVH"
and MONTH(fail_time) = 4 AS B
ON A.orders_id=B.orders_id
or you can refer to this link for a similar question
joining two select statements

Related

Selecting columns from table after joining in SQL [duplicate]

This question already has answers here:
Should I Always Fully Qualify Column Names In SQL?
(11 answers)
JOIN - Is it a good practice to add table name before column name?
(3 answers)
Closed 6 months ago.
is there a difference between specifying the table-column after joining tables?
For example, in the below queries I selected the columns as b.refunded_at or refunded_at. The output the same, but I just want to make sure.
Thanks
SELECT billing_cycle_in_months,
MIN(DATEDIFF(refunded_at, settled_at)) AS min_days,
AVG(DATEDIFF(refunded_at, settled_at)) AS avg_days,
MAX(DATEDIFF(refunded_at, settled_at)) AS max_days
FROM noom_signups AS a
JOIN noom_transactions AS b ON a.signup_id = b.signup_id
JOIN noom_plans AS c ON a.plan_id = c.plan_id
WHERE started_at >= 2019-01-01
GROUP BY 1;
and
SELECT billing_cycle_in_months,
MIN(DATEDIFF(b.refunded_at, b.settled_at)) AS min_days,
AVG(DATEDIFF(b.refunded_at, b.settled_at)) AS avg_days,
MAX(DATEDIFF(b.refunded_at, b.settled_at)) AS max_days
FROM noom_signups AS a
JOIN noom_transactions AS b ON a.signup_id = b.signup_id
JOIN noom_plans AS c ON a.plan_id = c.plan_id
WHERE a.started_at >= 2019-01-01
GROUP BY 1;
Tables do not have to be specified so long as the column names are unambiguous.

MySQL count how many times foreign key has a given value [duplicate]

This question already has answers here:
Selecting users who were not sent newsletter
(2 answers)
Closed 5 years ago.
I have one table with states and one table with dates under a given state
s_state
---------
#id name
1 State 1
2 State 2
d_date
--------
#date #user state
2017-01-01 1 1
2017-01-02 1 1
2017-01-03 2 1
I am trying to get, for a given user, how many times (how many days) he had been with each state. My current query works if the state is used, but my problem is that it doesn't return "count 0" for the states not used. (It would, for user 1, return only "State 1 used 2 times", but I want it to return "State 1 count = 2, State 2 count = 0")
Here is my current query:
SELECT s_state.id, COUNT(date)
FROM s_state
LEFT JOIN d_date ON s_state.id = d_date.state
WHERE d_date.user = 1
GROUP BY s_state.id
Try this
SELECT
s_state.id AS 'State Id',
IFNULL(COUNT(date), 0) AS 'Count'
FROM s_state
LEFT JOIN d_date ON s_state.id = d_date.state AND user = 1
GROUP BY
s_state.id,
user
If you use user in WHERE clause, it will filter those that do not exist. A JOIN will show NULLs instead, which you can then convert to 0s

Mysql inq - querying multiple tables for results

I'm working on a issue tracking script and looking at the mysql statement I was able to get the counts of all the priority issues but got stuck with getting the count on the status.
How do I go about retrieving the status count using the mysql statement below?
tbl_status
index status
1 open
2 closed
3 pending
tbl_priority
index priority
1 low
2 medium
3 high
tbl_incident
incident priority status
adfadf 1 2
adfsdf 2 2
adfadf 1 1
adfadf 3 2
adfasdf 1 3
I was able to group the priority as such (works):
Low 3
Hedium 1
high 1
Like the same results with status but its not working out. maybe asking too much from a single statement.
open 1
closed 3
high 1
try
{ $stmt = $dbcon1->query("SELECT COUNT(tbl_incident.status),
tbl_priority.priority, count(tbl_incident.priority), tbl_status.status
FROM tbl_incident
LEFT JOIN tbl_priority
ON tbl_priority.index = tbl_incident.priority
LEFT JOIN tbl_status
ON tbl_status.index = tbl_incident.status
GROUP BY tbl_priority.pry_priority ");
$priorityCount = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
maybe asking too much from a single statement.
Yes, try to separate statements for each question. It will be more efficient on my opinion.
For statuses:
select tbl_status.status, count(*)
from tbl_incident
inner join tbl_status on tbl_status.index = tbl_incident.status
group by tbl_status.status;
And for priority:
select tbl_priority.priority, count(*)
from tbl_incident
inner join tbl_priority on tbl_priority.index = tbl_incident.priority
group by tbl_priority.priority;

Return n number of rows from SQL Server query [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Row Offset in SQL Server
I have a query which has a like condition and it returns around 1500 rows. Now I want to know how can I get the rows part by part, e.g. return 75 rows, then again the next 75 rows until it reaches the end of the rows. I know I can use something like SELECT TOP 75
I tried something like this but it does not return any rows
SELECT *
FROM
(SELECT ROW_NUMBER() OVER (ORDER BY WarehouseSubType.id) as row,
WarehouseSubType.id,
WarehouseType.name as WarehouseTypename,
WarehouseType.alternateName AS WarehouseTypealternateName,
WarehouseSubType.name AS WarehouseSubTypename,
Warehouse.alternateName AS WarehousealternateName,
WarehouseSubType.alternateName AS WarehouseSubTypealternateName,
WarehouseSubType1.name AS WarehouseSubType1name,
WarehouseSubType1.alternateName AS WarehouseSubType1alternateName,
Warehouse.alternateName AS Warehousename,
Branch.name AS Branchname,
Branch.alternateName AS BranchalternateName,
WarehouseProductQuantity.actualQuantity,
WarehouseProductQuantity.reservedQuantity,
Supplier.companyName,
Supplier.companyNameAlternate,
Tafsil.description,
Tafsil.alternateDescription,
(WarehouseProductQuantity.actualQuantity - WarehouseProductQuantity.reservedQuantity) AS quantity
FROM WarehouseSubType
INNER JOIN WarehouseType ON (WarehouseSubType.warehouseTypeId = WarehouseType.id)
INNER JOIN WarehouseSubType1 ON (WarehouseSubType.id = WarehouseSubType1.warehouseSubTypeId)
) a
WHERE
warehouseTypename like '%Ve%'
AND row > 0 and row < 75
The code you posted should not even compile, let alone return rows. The sub query is not closed and row would not be recognised in the inner query.
Try this instead:
SELECT * FROM
( SELECT ROW_NUMBER() OVER (ORDER BY WarehouseSubType.id) as row,
WarehouseSubType.id,
WarehouseType.name as WarehouseTypename,
WarehouseType.alternateName AS WarehouseTypealternateName,
WarehouseSubType.name AS WarehouseSubTypename,
Warehouse.alternateName AS WarehousealternateName,
WarehouseSubType.alternateName AS WarehouseSubTypealternateName,
WarehouseSubType1.name AS WarehouseSubType1name,
WarehouseSubType1.alternateName AS WarehouseSubType1alternateName,
Warehouse.alternateName AS Warehousename,
Branch.name AS Branchname,
Branch.alternateName AS BranchalternateName,
WarehouseProductQuantity.actualQuantity,
WarehouseProductQuantity.reservedQuantity,
Supplier.companyName,
Supplier.companyNameAlternate,
Tafsil.description,
Tafsil.alternateDescription,
(WarehouseProductQuantity.actualQuantity - WarehouseProductQuantity.reservedQuantity) AS quantity
FROM WarehouseSubType
INNER JOIN WarehouseType
ON ( WarehouseSubType.warehouseTypeId = WarehouseType.id)
INNER JOIN WarehouseSubType1
ON (WarehouseSubType.id = WarehouseSubType1.warehouseSubTypeId)) a
WHERE warehouseTypename like '%Ve%' ) b
WHERE b.row > 0 and b.row< 75

How do I compare two queries by two columns in MySQL?

What's the best way to compare two queries by two columns? these are my tables:
This table shows exam questions
idEvaluation | Question | AllowMChoice | CorrectAnswer|
1 1 0 3
1 2 1 4
1 2 1 5
1 3 0 9
This table shows a completed exam
idExam| idEvaluation | Question | ChosenAnswer|
25 1 1 2
25 1 2 4
25 1 2 5
25 1 3 8
I have to calculate the percentage of correct Answers, considering to certain questions may allow multiple selection.
Correct Answers / Total Answers * 100
thanks for your tips!
This code will show you a listing of Questions and whether or not they were answered correctly.
select
A.Question,
min(1) as QuestionsCount,
-- if this evaluates to null, they got A) the answer wrong or B) this portion of the answer wrong
-- we use MIN() here because we want to mark multi-answer questions as wrong if any part of the answer is wrong.
min(case when Q.idEvaluation IS NULL then 0 else 1 end) as QuestionsCorrect
from
ExamAnswers as A
left join ExamQuestions as Q on Q.Question = A.Question and Q.CorrectAnswer = A.ChosenAnswer
group by
A.Question -- We group by question to merge multi-answer-questions into 1
Output Confirmed:
Note, the columns are intentionally named this way, as they are to be included as a subquery in part-2 below.
This code will give you the test score.
select
sum(I.QuestionsCorrect) as AnswersCorrect,
sum(I.QuestionsCount) as QuestionTotal,
convert(float,sum(I.QuestionsCorrect)) / sum(I.QuestionsCount) as PercentCorrect -- Note, not sure of the cast-to-float syntax for MySQL
from
(select
A.Eval,
A.Question,
min(1) as QuestionsCount,
min(case when Q.idEvaluation IS NULL then 0 else 1 end) as QuestionsCorrect
from
ExamAnswers as A
left join ExamQuestions as Q on Q.Question = A.Question and Q.CorrectAnswer = A.ChosenAnswer
where
A.Eval = 25
group by
A.Question, A.Eval) as I
group by
I.Eval
Output Confirmed:
This will communicate the general concept. Your column names idEvaluation and Eval are difficult for me to understand, but I'm sure you can adjust the code above to suit your purposes.
Note, I did this in sql server, but I used fairly basic SQL functionality, so it should translate to MySQL well.