Selecting Distinct Using SQLite package in R - mysql

I've been charged with finding how many telecasts does each series have?
I have the following tables from which to choose from:
So far I've gotten the following:
sql <- "select series_name, sum(telecast_id) from telecast group by
series_name limit 10"
res <- dbSendQuery(con, sql)
df_tc <- dbFetch(res)
print(df_tc)
It returns too many values though.
Any suggestions?

sum returns the total of the values in the brackets. So you're adding up the telecast IDs and getting large values. To determine "how many", as in "how many records", you need to use count(). If you assume that no record has a NULL telecast ID, then leave the column name blank inside the brackets. I've also named the result ("As n") but that's optional. And why limit the top 10? That was not specified in the question, so delete it.
sql <- "Select series_name, count() As n from telecast group by series_name"
The other commands seem ok.

Related

Access Mark a Record if Just One Record Contains a Specific Value

My Current Database
I would like to add a field that classifies each student by whether or not they failed a course. For example, if they failed a class the new field might have them marked as 'x'. If a student did not fail any course they may be marked as 'y'. How do I do this? Thanks.
Calculate in query using nested query or domain aggregate function:
SELECT *, IIf(SELECT Count(*) FROM tablename AS Q1 WHERE Q1.PassOrFail = "Fail" AND Q1.Student_ID=tablename.StudentID)=0, "Y", "X") AS Cat
FROM tablename;
or
SELECT *, IIf(DCount("*", "tablename", "PassOrFail = 'Fail' AND Student_ID=" & [Student_ID])=0, "Y", "X") AS Cat
FROM tablename;
Domain aggregate functions can cause slow performance in large dataset.

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).

Trouble in SQL Summing a Word

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.

How can I get just the column names for a given mysql query?

I am creating a utility which lets users enter a SQL query for the purposes of importing data to my database.
The first step is to show a list of resulting fields so the user can route them to the destination fields.
When users import from MSSQL, I can use SET FMTONLY ON to fetch the list of output columns that the query would produce if ran (assuming the query is valid in the first place).
I haven't been able to find a way to do this for MySQL. EXPLAIN doesn't list the resulting fields.
Given the following query:
SELECT CONCATENATE(first_name, " ", last_name) AS name, age, foo
FROM customers
ORDER BY name ASC;
I ultimately need to get a list of output fields only, like this:
{ "name", "age", "foo" }
How can I do this in MySQL?
SET FMTONLY ON still requires you to get the column names and types manually, it just generates an empty result set.
For MySQL, add a WHERE FALSE somewhere
SELECT CONCATENATE(first_name, " ", last_name) AS name, age, foo
FROM customers
WHERE FALSE
ORDER BY name ASC;
You get this lovely execution plan
"id";"select_type";"table";"type";"possible_keys";"key";"key_len";"ref";"rows";"Extra"
"1";"SIMPLE";NULL;NULL;NULL;NULL;NULL;NULL;NULL;"Impossible WHERE"
Then parse the columns as you would set fmtonly on with MSSQL
For complex queries (nested, group by, limit-ed), wrap it in a subquery
select * from (
<your wonderful brilliant complex query>
) x where false
MSSQL would have complained if the inner query contains ORDER BY without TOP, MySQL is ok with it.
I think you need to look at the resultsetmetada. I carries the number of columns, column name, and a few more about the result set.
I think you're looking for DESC {table_name}

I need some help getting MySql to output some results using a subquery

I'm storing a list of numbers inside a table as a varchar(255) and want to use this list in another query's "IN() clause.
Here's what I mean:
Table Data:
CREATE TABLE IF NOT EXISTS `session_data` (
`visible_portf_ids` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `session_data` (`visible_portf_ids`) VALUES
('45,44,658,659,661,45,44,658,659,661')
I want to run a query like this to return a list of portfolio's "QUERY #1":
SELECT portfolio_hierarchy_id, account_id, name, leaf_node_portf_id
FROM portfolio_hierarchy
WHERE account_id = 1
AND leaf_node_portf_id IN
(
(SELECT visible_portf_ids
FROM session_data
WHERE username = 'ronedog')
)
ORDER BY name ASC
The result of the query above returns only 1 row, when there are a total of 3 that should have been returned.
If I run the subquery alone like this:
(SELECT visible_portf_ids
FROM session_data
WHERE username = 'ronedog')
it will return a list like this:
45,44,658,659,661,45,44,658,659,661
But, when I run Query #1 above, only one row of data, which is associated with the "visible_portf_ids" of "45" is returned.
If I replace the subquery with hard coded values like this:
SELECT portfolio_hierarchy_id, account_id, name, leaf_node_portf_id
FROM portfolio_hierarchy
WHERE account_id = 1
AND leaf_node_portf_id IN (45,44,658,659,661,45,44,658,659,661)
ORDER BY name ASC
then I get all 3 rows I'm expecting.
I'm guessing that MySql is returning the list as a string because its stored as a varchar() and so it stops processing after the first "visible_portf_ids" is found, which is "45", but I'm not really sure.
Anyone got any ideas how I can fix this?
Thanks in advance.
You should think about restructuring your tables storing each value in a new row, instead of concatenating them.
Until then, you can use the FIND_IN_SET() function:
AND FIND_IN_SET(leaf_node_portf_id,
(SELECT visible_portf_ids
FROM session_data
WHERE username = 'ronedog'
LIMIT 1)
) > 0
Unfortunately MySQL does not have a function to split a delimited string. Your IN argument is a single string with the result of your subquery. The reason it works when you hard-code it is that MySQL is parsing the values.
I suggest that you redesign your data base to store the visible ports list as separate rows in a separate table. Then you can retrieve them and use them in subqueries like you tried.