I have this simple MySQL statement:
SELECT
((AVG(q1) + AVG(q8) + AVG(q15)) / 3 ) AS Res
FROM tresults
WHERE id = '1' AND date = 'MARCH2010' AND q25 = '1'
GROUP BY q25
Now, if there are no rows with the date MARCH2010 then the query returns zero results (which is correct) but I'd like it to return a row - even if the result is NULL.
You can just select a single row as a constant, and then left join it to your result set:
select l.*, r.*
from (select "your constant" as constant) as l
left join (
SELECT
((AVG(q1) + AVG(q8) + AVG(q15)) / 3 ) AS Res
FROM tresults
WHERE id = '1' AND date = 'MARCH2010' AND q25 = '1'
GROUP BY q25
) as r on 1
How this works:
select "your constant" as constant always returns a single row
left join always returns all of the rows in the left table at least once
if the right table has no rows, then the entire left table is extended with a bunch of null columns, and the result has one row
if the right table has n rows, the result has n rows that each have an additional "your constant" column
I'm not absolutely positive, but this case statement might work. I can't test it atm.
Case When
(SELECT
Count(*)
FROM tresults
WHERE id = '1' AND date = 'MARCH2010' AND q25 = '1'
GROUP BY q25) > 0
Then
SELECT
((AVG(q1) + AVG(q8) + AVG(q15)) / 3 ) AS Res
FROM tresults
WHERE id = '1' AND date = 'MARCH2010' AND q25 = '1'
GROUP BY q25
Else
SELECT null
End
SELECT
((AVG(q1) + AVG(q8) + AVG(q15)) / 3 ) AS Res
FROM tresults
WHERE id = '1' AND date = 'MARCH2010' AND q25 = '1'
GROUP BY q25
UNION ALL
SELECT NULL AS Res
FROM dual
WHERE NOT EXISTS (
SELECT
((AVG(q1) + AVG(q8) + AVG(q15)) / 3 ) AS Res
FROM tresults
WHERE id = '1' AND date = 'MARCH2010' AND q25 = '1'
GROUP BY q25
)
Will always return one row beacuse of second part.
Related
I have below table and SQL query written, this query should not return any result but its returning ID = 1 , what is wrong with the SQL query? Can anyone please help?
** Note balance data type is decimal rest are varchar
ID code balance level
1 C 150.00
1 P 40027.42 F
1 P 40027.42 F
select distinct ID from table
(
(code = 'P' and balance = 40027.42 and level = 'F') or
(code = 'C' and balance = 151.00 )
)
group by ID
having count(ID) >=2
If you do not want to count the same code twice, you can use count(distinct code):
select ID
from t
where (code = 'P' and balance = 40027.42 and level = 'F')
or (code = 'C' and balance = 151.00 )
group by ID
having count(distinct code) >=2
If you want to only count a distinct set of values once, you can use a derived table/subquery to select distinct rows:
select ID
from (
select distinct id, code, balance, level
from t
) as s
where (code = 'P' and balance = 40027.42 and level = 'F')
or (code = 'C' and balance = 151.00 )
group by ID
having count(ID) >=2
rextester demo for both: http://rextester.com/LBKO57534
I have two tables that I count rows of them.
SELECT COUNT(*)
FROM docgrados_directores
WHERE docgrados_directoresleido = '0' AND docgrados_directoresusu = '11'
result 1
SELECT COUNT(*)
FROM docgrados_lectores
WHERE docgrados_lectoresleido = '0' AND docgrados_lectoresusu = '11'
result 1
I need total count (result would be 2). How can I sum the result with a single statement? What is the correct syntax??
Use another SELECT to add the scalar values returned by your queries:
SELECT (SELECT COUNT(*)
FROM docgrados_directores
WHERE docgrados_directoresleido = '0' AND docgrados_directoresusu = '11' )
+
(SELECT COUNT(*)
FROM docgrados_lectores
WHERE docgrados_lectoresleido = '0' AND docgrados_lectoresusu = '11')
The above statement should return 2 as result if the result of both subqueries is a 1.
The below data shows time schedule having elective/ non-elective subjects of a student. My requirement is to select those rows when both elec and nonelec type has same period so in this case select elec type. Means for a day's schedule elective (type elec) should be given preference when both having same period. And when type elec does not has period like period 5 then select the non-elective one.
My Query
SELECT s.sch_id, s.sch_subtype, sd.sdetail_id, sd.sdetail_period
FROM schedule s
INNER JOIN schedule_detail sd ON s.sch_id = sd.sdetail_schedule
WHERE '2014-04-30'
BETWEEN sch_datefrom
AND sch_dateto
AND
(
(
sch_section =1
AND sch_subtype = 'nonelec'
)
OR
(
sch_subtype = 'elec'
AND 272
IN
(
SELECT edetail_stuid
FROM elective_detail
WHERE edetail_elective = sch_section
)
)
)
AND sch_course =3
AND sch_batch =2
AND sch_termid =2
AND sdetail_day = 'wed'
AND sdetail_period >0
AND CASE WHEN sch_subtype = 'nonelec'
THEN 1 =1
WHEN sch_subtype = 'elec'
THEN sdetail_subject >0
AND sdetail_faculty >0
AND sdetail_room >0
END GROUP BY CASE WHEN sch_subtype = 'elec'
THEN sdetail_period
ELSE 1
END ORDER BY sdetail_period
Output of above query
Required Output
You can try something of this sort :
SELECT sch_id,sch_subtype,sdetail_id,sdetail_period
FROM table
WHERE condition
group by sch_subtype
It would be better if you can post the query which u tried.
Dont really get whats the problem here:
SELECT * FROM schedule s
JOIN schedule_detail sd ON s.sch_id = sd.sdetail_schedule
LEFT JOIN elective_detail ed ON sd.sch_section = ed.edetail_elective
WHERE
(
sd.sch_section =1
AND s.sch_subtype = 'nonelec'
)
OR
(
ed.edetail_stuid = 227
AND sch_subtype = 'elec'
)
GROUP BY sd.sdetail_period
SQL Fiddle: http://sqlfiddle.com/#!2/69d4e/1
Here's my select:
SELECT
SUM(t.amount + c.designFeeValue) as cashReceived,
ROUND(SUM(i.value) * (m.percentOurs / 100)) as adValue,
m.managementFee as managementFee,
m.productionCost as productionCost,
5 as emailAddress,
(
(
SELECT value
FROM commission_transactions
WHERE isDebit IS
TRUE
) -
(
SELECT value
FROM commission_transactions
WHERE isDebit IS
FALSE
)
) as miscExpenses,
(managementFee + productionCost + emailAddress + miscExpenses) as totalExpenses
This is bombing because of the following line, where I add up some aliases.
(managementFee + productionCost + emailAddress + miscExpenses) as totalExpenses
The aliases are unknown fields.
Is there a way I can keep the aliases for this arithmetic or do I need to re-do all the math that generates each alias for the calculation of totalExpenses? That seems like a very ugly way to do it.
UPDATE:
Per your suggestions, I am now using a derived table.
SELECT
cashReceived,
adValue,
managementFee,
productionCost,
emailAddress,
miscExpenses,
adValue + managementFee + productionCost + emailAddress + miscExpenses as totalExpenses
FROM (
SELECT
SUM(t.amount + c.designFeeValue) as cashReceived,
ROUND(SUM(i.value) * (m.percentOurs / 100)) as adValue,
m.managementFee as managementFee,
m.productionCost as productionCost,
5 as emailAddress,
(
(
SELECT value
FROM commission_transactions
WHERE isDebit IS TRUE
) -
(
SELECT value
FROM commission_transactions
WHERE isDebit IS FALSE
)
) as miscExpenses
FROM magazines m
JOIN insertions i ON i.magazineId = m.id
JOIN transactions t ON t.insertionId = i.id
JOIN contracts c ON i.contractId = c.id
JOIN commission_transactions ct ON m.id = ct.magazineId
WHERE m.id = 17
AND t.isChargedBack IS FALSE
AND t.`timestamp` >= '2013-08-01 00:00:00'
AND t.`timestamp` < '2013-09-01 00:00:00'
AND ct.createdDate >= '2013-08-01 00:00:00'
AND ct.createdDate < '2013-09-01 00:00:00'
) sub;
Aliases aren't available for re-use within the field list, e.g:
mysql> select 5 as five, five + 1 as six;
ERROR 1054 (42S22): Unknown column 'five' in 'field list'
You'll have to wrap the select with another one, then do your alias math in that wrapper, e.g.
select *, managementFee + productionCost + emailAddress + miscExpenses) as totalExpenses
FROM (
... your above query here ...
)
I have some thing to do here with subquery but I am not able to do.
I want the result from a table with a extra field to show to no of results from other table with a column value from table 1.
table1:
CountryId Country ISO2 ISO3
table2:
id noof_country state
I have to retrive noof_country count in table 1 as count field
EDIT
my actual tables are
table 1:
ad_id job_country status delete days_left
table 2:
CountryId Country ISO2 status
I have done query in two phase:
$sql_map = "select distinct c.ISO2, c.Country, a.job_country
from rec_countries c, rec_advert a
where c.status = 1
and DATE(a.modified_date) >= CURDATE() - INTERVAL 30 DAY
and c.ISO2 <> '--'
and c.ISO2 <> ''
and c.CountryId = a.job_country
and a.status = 1
and a.`delete` = 0
and a.days_left >0
";
$res = mysql_query($sql_map);
while($row = mysql_fetch_array($res)){
$jobs_no = count($row['job_country']);
$sql_job = "SELECT COUNT( job_country ) AS jobs_no
FROM rec_advert
WHERE job_country = ".$row['job_country']."
and status = 1
and `delete` = 0
and days_left >0";
$resjob=mysql_query($sql_job);
$rowjob = mysql_fetch_array($resjob);
//here jobs_no is the count of total rows
}
Here I want to do with subquery.
If I read the question right, this should work:
SELECT
CountryId,
Country,
ISO2,
ISO3,
(
SELECT COUNT(DISTINCT noof_country)
FROM table2
WHERE table2.id = table1.CountryId
) AS noof_country_count
FROM table1
It's not immediately clear in your question which column in table1 is a foreign key to which column in table2... or if they are even related that way. If this query doesn't work for you, please clarify your schema.
Based on your updated information, try this:
select distinct c.ISO2, c.Country, a.job_country,
(
select COUNT(a2.job_country)
from rec_advert a2
where a2.job_country = a.job_country
and a2.status = 1
and a2.`delete` = 0
and a2.days_left >0
) as jobs_no
from rec_countries c, rec_advert a
where c.status = 1
and DATE(a.modified_date) >= CURDATE() - INTERVAL 30 DAY
and c.ISO2 <> '--'
and c.ISO2 <> ''
and c.CountryId = a.job_country
and a.status = 1
and a.`delete` = 0
and a.days_left >0