MYSQL query - Counting Values in columns dynamically - mysql

I want to write a query to pull a certain set of results. While doing that I want to be able to keep a count of number of occurrences of a certain value in a certain field. I'm trying to pull a record of part-numbers from a table for devices, There are various partnumbers that are pulled from tables.
For instance this is my result set
CISCO1841
CISCO2610
CISCO2650
CISCO2610
CISCO2650
CISCO2500
I should keep track that
CISCO1841 occured one time, CISCO2610 occured twice, CISCO2650 occured twice and CISCO2500 occured once. I need to store this count and set another column value based on this count. Is there an efficient way to do this in MYSQL?

Group your query and COUNT() the results:
SELECT myColumn, COUNT(*) FROM myTable GROUP BY myColumn
See it on sqlfiddle.

You can use a trigger on the table where your data is inserted and that trigger will keep count of the occurrences by updating the counter for each word (ex : CISCO2650) in a separate table.
Or you can try a query like below but its not dynamic :
SELECT
SUM(IF(M_PART_NBR = 'CISCO2610',1,0)) as NBR1,
SUM(IF(M_PART_NBR = 'CISCO2811',1,0)) as NBR2,
SUM(IF(M_PART_NBR = 'CISCO2911',1,0)) as NBR3
FROM
C2_INST_PRODUCT WHERE M_PART_NBR LIKE '%CISCO2%'

Related

How to query the database to display the most data only?

i have table like this
Table
I just want to display the data based on the most data appearing in the second field and I do not want to display a little data. So the data appears only the most and count the total value in the third field. And I've tried but no results.
How to query the database to display the most data only
You can do something like this,
SELECT `col_name_of_frequent_value`,
COUNT(`col_name_of_frequent_value`) AS `frequent_value`
FROM `table_name`
GROUP BY `col_name_of_frequent_value`
ORDER BY `frequent_value` DESC // This will sort the result by putting max count at top.
LIMIT 1; // This will only show the TOP-Most value in sorted result.
Please change the names as per your table structure.
SELECT
kd_masalah, total_bobot
FROM
(SELECT -- SubQuery
SUM(bobot) AS total_bobot, -- Gives the sum of values in bobot column relating to a particular group (grouped column)
kd_masalah
FROM
your_table_name
GROUP BY kd_masalah -- Grouping of same values in the column
)AS s having MAX(total_bobot); -- return the values having max sum in total_bobot

Trying to avoid duplicate SQL entries

I am trying to avoid adding a certain game's data to my table more than once so I am trying to make an if statement that would check if that game's ID is already in the table, however for some reason the if statement is always false. This is my code:
$a = $_GET['id'];
$colname = $_GET['colname'];
$b = "SELECT count(*)
FROM table
WHERE gameid = ".$a;
if($dup = mysqli_query($dbc, $b)){
if(mysqli_num_rows($dup)==0){
$insrt = "INSERT INTO table ($colname)
VALUES ($a)";
mysqli_query($dbc, $insrt);
}
}
If I were you, instead of using logic within your program to avoid creating duplicate entries, I would simply tell MySQL that your ID column should be unique. Take a look at the info on column definitions in the MySQL Reference Manual, specifically the keywords UNIQUE or PRIMARY KEY.
If you specify that your ID column should be a unique index, then MySQL will prevent another entry with the same ID value from being added. That way, in your program, you can simply attempt to add the data, and the procedure will automatically fail if it is a duplicate. As an added bonus, this means you'll only have to do one query from your program instead of two.
A SELECT COUNT().... query, barring exceptional circumstances, is generally going to return at least one row (more if there is a GROUP BY clause that would indicate otherwise); you need to check that the field value is 0, not that there are no rows in the result.
Change your query to remove the aggregate, and just return a column, e.g.
SELECT gameid
FROM table
WHERE gameid = ?
LIMIT 1
You don't need a count of rows, you just need to know whether a row is returned.
Or, you could add a HAVING clause to your query to not return a row when the COUNT is zero...
SELECT COUNT(*)
FROM table
WHERE gameid = ?
HAVING COUNT(*) > 0
There's no need for you to retrieve the value of the column from the row that's returned, just return an empty resultset, and test whether the resultset is empty, like your code is doing.

Subquery returns more than 1 row solution for update query using select statement

Hello i have query in which i have written update statement using select statement. But unfortunately getting errors subquery returns more than 1 row. I know where the error is coming. But i dont know solution for the same.Thank you.
Here is the query:
UPDATE adsetest.dashboard_widget_users
SET configuration=
(SELECT DISTINCT ad_news_texte.headline
FROM autodo.ad_news_texte
INNER JOIN autodo.ad_news_oe
ON ad_news_texte.news_id = ad_news_oe.id_ad_news
INNER JOIN autodo.ad_news
ON ad_news_oe.id_ad_news = ad_news.id
WHERE ad_news.datum_archiv BETWEEN
curdate() - INTERVAL DAYOFWEEK(curdate()) + 28 DAY AND curdate())
WHERE dsnr_yw_user = 1 AND dsnr_dashboard_widget = 1
When you use update with SET configuration=(SELECT ...) the subquery has to return no more than one value (one row). If it returns more than one value how do you assign two rows table for example to scalar configuration field. So you should figure out WHY your subquery returns more than one row and fix the subquery or decide which ONE value to select for update in case of more than one row. For example you can select maximum value
SELECT MAX(ad_news_texte.headline)...
or any one first value
(SELECT ad_news_texte.headline)... LIMIT 1)
and so on...
If you need to concatenate all rows and put it into one row configureation you can use GROUP_CONCAT() mysql function:
SET configuration=(SELECT GROUP_CONCAT(DISTINCT ad_news_texte.headline) FROM ....
You have to first think about what you want to do.
Do you want to fetch one value and save it somewhere else?
Then use SET value = (SELECT...). For this you need to make sure, the inner statement doesn't return more than one value.
Or
Do you need to be able to handle fetching multiple values?
What do you want to do with these? Save all of them? All in one (use concat) or store them individually (one update per result)? Or select one of them? Maybe the first (LIMIT 1) or highest (MAX) or lowest (MIN) value?

How can I select the second last and last row from the database?

When we are retrieving data from database, we use something like this
SELECT * FROM Names
However, we will get all the data inside the specific table. Since I am going to update some data to the database and want to make a comparison bewteen the last row of data in the db and the most updated data, how can I select and retrieve the last two row of the database only?
If you were using SQL Server, you would do something like this:
SELECT TOP 2 * FROM Names ORDER BY Name DESC
SQL Server syntax:
SELECT TOP 2 column_name FROM table_name ORDER BY column_name DESC;
Example:
If you want to retrieve the last value of the customer_name column from the customers table, you need to write the following query:
SELECT LAST (CUSTOMER_NAME) AS LAST_CUSTOMER FROM CUSTOMERS;
You should include a column in the Names table to keep track of when a name was added to the table since you cannot guarantee that the rows are in the order that they were inserted. With that column you can use the order by clause..
In MySQL Syntax:
SELECT *
FROM Names
ORDER BY order_column DESC
LIMIT 2;
If you want to get the last rows as they are, you cannot order the table by the inserted names because that is just getting the 2 names that come last in an alphabetically sorted list of names. You could try something like this where you include an offset in the limit clause if you get the number of rows in the table:
SELECT *
FROM Names
LIMIT *num_rows*-2, 2;
You would have to know the number of rows to use this query or use an additional query to implement a row count that works with limit. This, however, still may not be accurate since the system may not order the rows as they were inserted. I still recommend the first option where you keep track of order/time a name was inserted.

SQL combine COUNT and AVG query with SELECT

I need to get the average rating and the total number of ratings for a particular user and then select all single ratings (rating_value, rating_text, creator) as well:
$rating_query = mysql_query("SELECT COUNT(1) as rating_count
,AVG(rating_value), rating_value, rating_text, creator
FROM user_rating WHERE rated_user = $user_id");
This query would return the COUNT(1) result and the AVG(rating_value) for every row, but I only need those values once.
Is there any way to do this without making 2 separate queries?
There may be a trick I'm not aware of, but I don't think that's possible to do in a single query. You could try using a GROUP BY clause if that would make sense for you, but I'm guessing it probably doesn't from the column names you're using. Any relation requires a single atomic value at any given row and column, even if that value is null. What you are requesting is that columns 1 and 2 in every row but the first have no value, and again I don't think this is possible.