sql count the date less than current date - mysql

I have a table where user input a target date, and then I want to output the count of names where their associated target date is greater than current date.
I tried but I'm getting the same results
below is the code
$select1_query = "
SELECT ACCOUNT_NAME
, COUNT(NCI_NUMBER)
, COUNT(CURDATE()>TARGET_DATE)
FROM sim_tracker
WHERE NCI_STATUS != 'Closed'
GROUP
BY ACCOUNT_NAME
";

Don't use count(). Use sum():
SELECT ACCOUNT_NAME,
COUNT(NCI_NUMBER),
SUM(CURDATE() > TARGET_DATE)
FROM sim_tracker
WHERE NCI_STATUS <> 'Closed'
GROUP BY ACCOUNT_NAME;
This works because MySQL treats booleans expressions as "1" for true and "0" for false in a numeric context. SUM() then counts the number of "true" values.
COUNT() does not work, because COUNT(<expression>) counts the number of non-NULL values. "true" and "false" are both non-NULL, so they both get counted.

Related

SSRS Expression to Sum value IIF YearMonth = Parameter

I hope someone would be able to assist\help.
I have a Tablix that I'm trying to populate with three separate (summed) values (Current Month, Current Year and Previous Year) from one field based on a parameter. My parameter is set as yyyymm. My expression logic is as follows for each summed value:
Sum Current Month values
=SUM(Fields!Quantity.Value),IIF(Parameters!YearMonth.Value) = CDATE(Now()), "yyyyMM")
Sum Current Year values
=SUM(Fields!Quantity.Value),IIF(Parameters!YearMonth.Value) = CDATE(Now()), "yyyy")
Sum Previous Year values
=SUM(Fields!Quantity.Value),IIF(Parameters!YearMonth.Value) = CDATE(Now()), "yyyy")-1
I'm getting the following error when attempting the above expressions:
The Value expression for the textrun Quantity5.Paragraphs[0].TextRuns[0] contains an error: [BC30205] End of statement expected
As Harry pointed out, the IIF statement syntax is
IIF([Expression to evalute], [Expression to return if true], [Expression to return if false])
Also, I think you need to format the date you get back from now() so it matches the format of your parameter.
So, taking your first expression it should be something like
=SUM(
IIF(Parameters!YearMonth.Value = FORMAT(Now(), "yyyyMM"), Fields!Quantity.Value, Nothing)
)
So starting at the inner expression, we compare the parameter to today's date formatted as yyyyMM. If the match the return the value of the Quantity field, if not return nothing.
The outer SUM then just sums all these results.

outputing greatests() timestamps returns nulls sql, mysql

I have three dates data_a,date_b & date_main. All of them TIMESTAMP that outputs values likes this 2018-06-20 11:11:20.
Sometimes date_a or date_b are NULL, date_main is always present (NOT NULL).
Why when trying to compare them using GREATEST(), it outputs blanks (NULL) values ""?
GREATEST(MAX(l.date_a),MAX(r.date_b),p.date_main) AS date,
You could use COALESCE to handle NULL values for every column that is nullable:
GREATEST(COALESCE(MAX(l.date_a), '1900-01-01'),
COALESCE(MAX(r.date_b), '1900-01-01'),
p.date_main
)AS date
As you want greatest value I would exchange NULL with some date from the past(arbitrary value).
If p.date_main is never NULL, I would use:
GREATEST(COALESCE(MAX(l.date_a), p.date_main),
COALESCE(MAX(r.date_b), p.date_main),
p.date_main
) AS date,
GREATEST() and LEAST() (unlike MIN() and MAX()) return NULL if any of the arguments are NULL. So, if all the values in a group are NULL, then MIN() and MAX() return NULL. The COALESCE() replaces the value with p.date_main for the comparison for the greatest value.

MySQLI SELECT with multiple clauses for epoch timestamps selection

I have epoch timestamps into "PART_EPOCH" column, table name is "crud_mysqli"
I would like to select associated "PART_ID" value for the next FUTURE timestamps. (avoid a research into past timestamps)
The following MySQLI query should select the MIN (next) value within the future : > now.
But it does not return anything.
It does return expected return if i state clauses seperately,
combining clauses as below returns no result.
Would you please tell me what is wrong here :
// Find next event PART_ID name :
// SELECT lowest (next) PART_ID value in the future (do not select winthin past PART_EPOCH values)
$query = "SELECT
PART_ID
FROM crud_mysqli
WHERE (PART_EPOCH = (SELECT MIN(PART_EPOCH) FROM crud_mysqli))
AND (PART_EPOCH > UNIX_TIMESTAMP(NOW()))
";
WHERE (PART_EPOCH = (SELECT MIN(PART_EPOCH) FROM crud_mysqli))
Here you say to only take the entry with the lowest timestamp, which is probably somthing in the past.
AND (PART_EPOCH > UNIX_TIMESTAMP(NOW()))
And here you say, that it should be in the future. The two conditions are excluding each other, if you have any entry with the timestamp in the future.
So you need to put the second condition into the subquery:
SELECT
PART_ID
FROM crud_mysqli
WHERE PART_EPOCH = (
SELECT MIN(PART_EPOCH)
FROM crud_mysqli
WHERE PART_EPOCH > UNIX_TIMESTAMP(NOW())
)
That means: "take the entry with the lowest timestamp in the past"
However.. you can as good do the following:
SELECT PART_ID
FROM crud_mysqli
WHERE PART_EPOCH > UNIX_TIMESTAMP(NOW())
ORDER BY PART_EPOCH ASC
LIMIT 1
The result would only differ if you have two entries with the same timestamp. In that case the first query would return both of them - the second query only one.

MySQL UPDATE not working when first subquery = 0

I have the following query to update my payment table in order to set it equal to the sum of all charges minus the sum of all payments and credits in a customer database.
This works perfectly as long as there is a charge, however, if the first subquery is equal to zero it does not update payment.balance to a negative number, it simply remains zero.
Can anyone tell me how to fix this or why this is?
UPDATE customer
SET balance = (SELECT SUM(amount)
FROM payment
WHERE type = 'C'
AND custID = '10003')
- (SELECT SUM(amount)
FROM payment
WHERE (type = 'P' OR type = 'X')
AND custID = '10003')
WHERE custID = '10003';
So in brief summary, when the first subquery (SELECT SUM(amount) FROM payment WHERE type = 'C' AND custID = '10003') is 0, the update always results in 0 instead of 0 minus the second subquery.
Thoughts?
Being that I cannot see your actual db table column setup I'm guessing this.
MySQL SUM() function returns the sum of an expression. SUM() function returns NULL when the return set has no rows.
Use an if condition so in the event that SUM() yields NULL then have the value returned as 0 so you never have NULL - x or x - NULL or NULL - NULL.

MySql Sub Select

I need to query a table and gather counts with and without a column value.
What is the count of records that contain column value on 'src' and the count without.
Problem
Results contain one day only instead of every day on each row. Each row has same values.
Results Expected
DAY, CONTAINS VALUE, DOESN'T CONTAIN VALUE
Query
SELECT
DATE_FORMAT(edate,'%Y-%m-%d') as day,
(SELECT
COUNT(id) FROM entries WHERE src='a string' and color = 'red') with_value,
(SELECT
COUNT(id) FROM entries WHERE src='' and color = 'red') without_value
FROM entries
GROUP BY day
ORDER BY day DESC
You can do it without subqueryes using this technique:
SELECT
DATE_FORMAT(edate,'%Y-%m-%d') as day,
SUM(src = 'a string') as with_value,
SUM(src = '') as without_value
FROM entries
GROUP BY day
ORDER BY day DESC
What I did there was take advantage of the fact that MySQL does not have a Boolean data type, but rather TRUE is identical to 1, and FALSE to 0, in effect having the SUM act as a COUNT of rows that satisfy the condition.
I would do this using conditional aggregation:
SELECT DATE_FORMAT(edate, '%Y-%m-%d') as day,
SUM(src = 'a string' and color = 'red') as with_value,
SUM(src = '' and color = 'red') as without_value
FROM entries
GROUP BY day
ORDER BY day DESC;
In MySQL boolean expressions are treated as 0 (for false) and (1 for true) in an integer context. This makes them convenient for aggregation.
If you want per-day aggregate results then you need to perform the grouping by day in the query(-ies) where you compute the aggregate(s). You are grouping in a parent query instead.
In any event, you don't need subqueries for this, and it would be better to avoid them:
SELECT
DATE_FORMAT(edate,'%Y-%m-%d') as day,
SUM(CASE WHEN src='a string' THEN 1 ELSE 0 END CASE)
AS with_value
SUM(CASE WHEN src='' THEN 1 ELSE 0 END CASE)
AS without_value
FROM entries
WHERE color = 'red'
GROUP BY day
ORDER BY day DESC