Trouble in SQL Summing a Word - mysql

I am trying to Sum() the column Status where Status = 'operational'. I am having trouble figuring out how to sum the actual word "operational".
I have tried multiple different variations of the statement below (the one I posted is the most basic form) but I get the error: data type varchar is invalid for sum operator.
Can anybody help?
SELECT SUM(status) As 'TotalOperationalSTIDevices'
FROM netinfo_device_details
WHERE LoopBackAddress LIKE '10.12%' AND Status = 'Operational'

Try
Select COUNT(*) As 'TotalOperationalSTIDevices' from netinfo_device_details where LoopBackAddress Like '10.12%' and Status = 'Operational'

You need to use COUNT:
SELECT COUNT(*) As TotalOperationalSTIDevices
FROM netinfo_device_details
WHERE LoopBackAddress LIKE '10.12%' AND Status = 'Operational';
The SUM aggregation function really does a SUM of a set of numbers. COUNT just counts the number of rows.
Since the actual content of the row is not relevant, you can use COUNT(*) instead of COUNT(status) if you want.

Related

SQL query problem for getting the details under a individual date or date range from datetime

The sql query I have is :
Select count(cf_1519) as service_up,createdtime
from vtiger_ticketcf,vtiger_crmentity
Where date(createdtime)=date(now()) and
vtiger_ticketcf.cf_1519 like 'service up%' and
vtiger_crmentity.crmid = vtiger_ticketcf.ticketid"
which gives result as
again if i want to search the result individualyl by the query :
Select count(cf_1519) as service_up,createdtime
from vtiger_ticketcf,vtiger_crmentity
Where date(createdtime)= '16/10/2019%' and
vtiger_ticketcf.cf_1519 like 'service up%' and
vtiger_crmentity.crmid = vtiger_ticketcf.ticketid"
the result is not similar similar to previous :
I want to get the result by individual search by date only or a date range , i dont need the time
what changes in the sql code is needed to be done?
Your second query should look more like this:
select count(cf_1519) as service_up, max(createdtime)
from vtiger_ticketcf t join
vtiger_crmentity c
on c.crmid = t.ticketid
Where date(createdtime) = '2019-10-16' and
t.cf_1519 like 'service up%';
Notes:
You have an aggregation query (because of the count(), but have extraneous columns. All columns should be aggregated, except for those in the group by (and there are none).
Never use commas in the from clause. Always use proper, explicit, standard JOIN syntax.
You seem to want to use string functions on dates. I have never seen a date with a percentage sign in it.
Use proper date/time functions on date/time values, not string functions.

Missing values in a query

I encounter some strange results in the following query :
SET #indi_id = 768;
SET #generations = 8;
SELECT num, sosa, seq, len, dernier, ful_ful_nom
FROM fullindi
LEFT JOIN lignee_new
ON ((ful_indi_id = dernier) AND (len BETWEEN 1 AND #generations))
RIGHT JOIN numbers
ON ((sosa = num) AND (premier = #indi_id))
WHERE num BETWEEN 1 AND pow(2, #generations)
GROUP BY num
ORDER BY num;
The result looks like this :
Why the row just before a full NULL one doesn't display the existing values 'sosa', 'len', 'dernier', ful_ful_nom') but only the 'seq' value (see rows 43 and 47 in this example) ?
What am I missing?
As requested, here are data :
table lignee_new :
table fullindi :
The problem is that MySQL does really dumb things when an Aggregate function is introduced, or a GROUP BY is included, but not all of the fields are in an Aggregate Function or your GROUP BY.
You are asking it to GROUP BY num but none of the other columns in your SELECT are included in the Group BY nor are they being aggregated with a function (SUM, MAX, MIN, AVG, etc..)
In any other RDBMS this query wouldn't run and would throw an error, but MySQL just carries on. It uses the logic to decide which value it should show for each field that isn't num by just grabbing the first value it finds in it's data storage which may be different between innoDB and whatever else folks use anymore.
My guess is that in your case you have more than one record in lignee_new that has a num of 43. Since you GROUP BY num and nothing else, it just grabs values randomly from your multiple records where num=43 and displays them... which is reasonable. By not including them in an aggregate function you are pretty much saying "I don't care what you display for these other fields, just bring something back" and so MySQL does.
Remove your GROUP BY clause completely and you'll see data that makes sense. Perhaps use WHERE to further filter your records to get rid of nulls or other things you don't need (don't use GROUP BY to filter).

select avg(),min(),max(),toatl(),count() of selected result

I am trying to calculate average,min,max,total,count but i am getting wrong result.
SELECT t0.brandID, t0.brandName, t0.cdt, t0.udt, t0.brandstatus, t0.AddedBy ,
AVG(t0.brandID) AS brandID_AVERAGE,
min(t0.brandid) as branid_min,
MAX(t0.brandid) as brandid_max,
COUNT(t0.brandid) as brandid_count
FROM brands t0
Where t0. brandID=null OR t0. brandName='khasim'
group by t0.brandID,t0.brandName,t0.cdt,t0.udt,t0.brandstatus,t0.AddedBy
select AVG(CAST (brandID AS bigint)) AS brandID_AVERAGE,
min(CAST (brandID AS bigint)) as branid_min,
MAX(CAST (brandID AS bigint)) as brandid_max,
COUNT(CAST (brandID AS bigint)) as brandid_count from
(SELECT t0.brandID, t0.brandName, t0.cdt, t0.udt, t0.brandstatus, t0.AddedBy
FROM brands t0
Where t0. brandID=null OR t0. brandName='budwieser'
group by t0.brandID,t0.brandName,t0.cdt,t0.udt,t0.brandstatus,t0.AddedBy) temptable
i have changed my query to select avg etc for the result of select now
i am getting what i expect, but i want to show all selected columns in
one table how to do.
expected result
result for the above query is
Firstly. From my best knowledge in SQL null is not equal to null. So you need to use is null to check is value equals to null.
Secondly. Could you explain please what is wrong with underlined values?
Your first query where you're returning one row looks correct. Your second screenshot where you get many rows looks like you are using WINDOWING functions (i.e. anything with an OVER clause). This does not aggregate data, it returns all rows and repeats the calculations over the set while returning every row.
Can you include the full query text that is producing the incorrect result?
Also, it could be caused by brandId being an integer type, in which case all calculations on it will use integer-based arithmetic (i.e. no fractions). This is fine if you only expect integer results, but if you need fractions, try using CAST to convert all the occurrences of brandid to decimal types, like this: CAST(brandId as decimal(18, 8)) before doing the AVG and other calculations.

Simple If Else statement in sql

I'm trying to get only the rows that are in USD and EUR from a table with more currencies.
I thought the code should be something like:
SELECT IF(CONTRACTS_IN_DIFFERENT_CURRENCIES.CURRENCY='USD',1,0) OR IF(CONTRACTS_IN_DIFFERENT_CURRENCIES.CURRENCY='EUR',1,0
FROM CONTRACTS_IN_DIFFERENT_CURRENCIES
But I know this is not how it should be. I would like the table to be something like a column of USD and EUR
It looks as though you're trying to use Excel's IF(condition, true_response, false_response) syntax. The equivalent in T-SQL is the CASE WHEN THEN ELSE END syntax:
SELECT
CASE
WHEN CONTRACTS_IN_DIFFERENT_CURRENCIES.CURRENCY ='USD' THEN 1
WHEN CONTRACTS_IN_DIFFERENT_CURRENCIES.CURRENCY='EUR' THEN 1
ELSE 0
END
FROM
CONTRACTS_IN_DIFFERENT_CURRENCIES
This will work with more complex queries than the example you're giving us. Another way of doing it, if you have a number of possible values for the same field that will return the same response, would be
SELECT
CASE
WHEN CONTRACTS_IN_DIFFERENT_CURRENCIES.CURRENCY IN ('USD','EUR') THEN 1
ELSE 0
END
FROM
CONTRACTS_IN_DIFFERENT_CURRENCIES
However, that is not the right syntax to use to get just the rows with certain currencies; the previous answer with
SELECT *
FROM
CONTRACTS_IN_DIFFERENT_CURRENCIES
WHERE
CONTRACTS_IN_DIFFERENT_CURRENCIES.CURRENCY IN ('USD','EUR')
would work best for that.
The preceding answers are good in my opinion, but let's say you would have alot of currencies, you could do
SELECT * FROM CONTRACTS_IN_DIFFERENT_CURRENCIES WHERE CURRENCY IN ("USD","EUR")
SELECT *
FROM CONTRACTS_IN_DIFFERENT_CURRENCIES WHERE
CONTRACTS_IN_DIFFERENT_CURRENCIES.CURRENCY='USD' OR CONTRACTS_IN_DIFFERENT_CURRENCIES.CURRENCY='EUR'
OR
SELECT *
FROM CONTRACTS_IN_DIFFERENT_CURRENCIES WHERE
`CONTRACTS_IN_DIFFERENT_CURRENCIES`.`CURRENCY`="USD" OR `CONTRACTS_IN_DIFFERENT_CURRENCIES`.`CURRENCY`="EUR"
I have not understand ,1,0) that part. So if you need some more condition use AND, OR and combination of brackets to achieve result.
Just to let you know, if you need disctinc (non repeating values) you can use word DISTINCT and state what fields exactly you need.
You need to use a WHERE clause.
As far as I can tell you're looking for a query along the lines of
SELECT * FROM `CONTRACTS_IN_DIFFERENT_CURRENCIES` WHERE `CURRENCY` = "USD" OR `CURRENCY` = "EUR"
If you want the count of the number of contracts in each of those currencies with each count as a column (which seems to be indicated by one of the comments in your question), then use this…
SELECT SUM(CURRENCY = 'USD') AS usdContracts,
SUM(CURRENCY = 'EUR') AS eurContracts
FROM CONTRACTS_IN_DIFFERENT_CURRENCIES
If you want the count of the number of contracts in each of those currencies with each count as a row with the count in one column and the currency abbreviation in another, then use this…
SELECT COUNT(*) AS numContracts, CURRENCY AS currency
FROM CONTRACTS_IN_DIFFERENT_CURRENCIES
WHERE CURRENCY = 'USD' OR CURRENCY = 'EUR'
GROUP BY CURRENCY;

MySQL select with subquery having replace

So I have a data with format like ;1;;2; and then I need to use this number in a query so I thought I'd convert it to 1,2 and use that in a IN condition. In my table, the result should return 2 rows but instead it is returning only 1 row.
My query is like this. The subquery return 1,2 with no problem but only 1 row is retrieve.
select *
from wt_lists
where id IN ((select replace (replace(sendto, ';;',','),';','')
from wt_stats where statsid IN (1)))
But when I try it with this. It returns the correct result, which in my case is 2 rows.
select *
from wt_lists
where id IN (1,2)
What am I missing here?
Comma delimited strings need to be explicitly defined in the query in order to be used in the IN clause - there's countless examples on SO where people need to use dynamic SQL to incorporate user submitted comma delimited strings.
That said, I have a solution using the FIND_IN_SET function:
SELECT DISTINCT wl.*
FROM WT_LISTS wl
JOIN (SELECT REPLACE(REPLACE(ws.sendto, ';;',','),';','') AS ids
FROM WT_STATS ws
WHERE ws.statsid = 1) x ON FIND_IN_SET(wl.id, x.ids) > 0
You are replacing the string:
';1;;2;'
To:
'1,2'
So, you SQL query looks like:
select * from wt_lists where id IN ('1,2') from wt_stats where statsid IN (1)
To use IN clause you need select different values in different rows.
I found this store procedure that does exactly what you need.
http://kedar.nitty-witty.com/blog/mysql-stored-procedure-split-delimited-string-into-rows/
I have not tested, but it is the way.
Obs: Like David said in the comments above, parsing the data in your application is a better way to do this.