Making an Update Query to Count Occurrences - count

I have a simple question about the SQL of an UPDATE query. I found something very close to what I want to know here:
MySQL: Count occurrences of distinct values
But.. it's not an update query. Here's the example of what I want to do:
In one table (let's call the table "data"), I want to make an UPDATE query. Here’s what the table looks like:
Id color count
1 blue 0
2 blue 0
3 red 0
4 red 0
5 blue 0
6 white 0
Now, [id] is the auto-incremental key for this example, [color] is a TEXT field. [count] is a number
What I want, is for the count to be UPDATED so that it tells how many instances a [color] occurs. After the UPDATE query runs, the table would look like this:
Id color count
1 blue 3
2 blue 3
3 red 2
4 red 2
5 blue 3
6 white 1
Looks pretty simple, but I've messed with the DCOUNT and COUNT commands, and I'm probably missing something very easy, but still... no joy. All the help I've seen only only deals with SELECT queries, but I will definitely need this query to update the [count] field.
Thanks in advance!

You should try :
UPDATE data JOIN
(
SELECT color, count(1) AS color_cnt
FROM data
GROUP BY color
) AS sub ON data.color = sub.color
SET cnt = sub.color_cnt

Related

creating a field with a count

How can I make a column with a count of records? I want to create something similar to Field1.
Field1 Field2
1 apple
1 apple
1 apple
2 orange
2 orange
2 orange
2 orange
This will give you a count of the records.
SELECT Count(*) FROM YourTableName;
I think you might be asking for a distinct count of Field2. This will give you that.
SELECT Count(Distinct Field2) FROM YourTableName;
Here is some documentation on count queries. http://www.w3schools.com/sql/sql_func_count.asp
And more detail and complex counts with group by. That might be what you are looking for also.
http://www.sqlteam.com/article/how-to-use-group-by-with-distinct-aggregates-and-derived-tables
Disregard, thanks everyone. I was able to solve my problem using the rank and dense_rank statements

SQLite: Select all Names of given Colors

I have an SQLite Database, two of the tables look like this:
ID Name
1 Test1
2 Test2
3 Test3
4 Test4
ID Color
1 Blue
1 White
1 Red
2 Green
2 Red
4 Black
In the first Tables, ID is unique, the second table lists colors an ID has, it can be from 0 to n colors.
Now I want to select all Names exactly once, that have one or more given color. Lets say, I want to have all names associated with blue, white and/or green. The resultset should have the IDs 1 and 2.
I am completly lost here, as I normally dont do any SQL. I am just familiar with very basic SQL. What I would do is Join the tables together, but I dont know how I do that, as ID is not unique in the second table. Also there would be the problem of IDs beeing duplicated in the resultset, if it has multiple colors that I want to select.
Thanks in advance for any help.
You don't need a join for this. Get the list of IDs from the color table in a subquery, and fetch the names from the test table with an in clause:
sqlite> select * from tests where id in
(select id from colors where name in ('Blue', 'White', 'Green'));
1|Test1
2|Test2
Duplicates don't matter in the subquery, but you could use distinct if you want that list without duplicates in other contexts.

How to select product with multiple categories

According my title of question so i have structure for Access database like this:
Category
categoryid categoryname
1 one
2 two
3 three
Product table:
productid productname categories
1 one 1,2,3
2 two 3
3 three 1,2
When i have categoryid is 1 I dont know the way to select product have multiple categorise. Because when i use In operator,i am getting some error..
Select * from product where categories In (categodyid) because cannot compare a collection with one value.
i'm stuck at here! Please help me! Thanks.
First of all, your tables are not normalized. Look at the Categories column in Product Table. Each cell should have only one value. By allowing multiple values, you risk various problems including update/insert anomalies and what you are seeing now. You also make it very difficult to do selects and other operations. Instead, think about normalizing your tables with this example:
Category
categoryid categoryname
1 one
2 two
3 three
Product
ProdductId ProductName
4 prod1
5 prod2
6 prod 3
Category_Prod
CategoryId ProductId
1 3
1 4
2 3
The third table acts as a way to remedy the many to many pattern. If you have any questions on how to do this or how to use it, let me know
This is a classic parent-child one-to-many relationship. You need a [ProductCategory] table to associate a given Product with multiple Categories:
productid categoryid
1 1
1 2
1 3
2 3
3 1
3 2

How to bulid a report with a total and breakout columns with SQL Server and Reporting Services

I have a data structure where I have two tables Alpha and Beta and they are one to many. For the sake of an example let's say that table alpha has a column for "State" and table B has "Colors you like" and you can pick more than one. I would like to build a report that has columns like this:
STATE TOTAL RED GREEN BLUE
Alaska 5 1 3 1
Florida 2 2 2 0
New York 10 5 8 1
The column TOTAL would be a count of the records in Alpha and as you can see due to the one to many relationship the sum of the colors can exceed the count. I suppose it could be less as well if people didn't like colors.
How would you build a report like this. I'll be using SQL Server and Reporting Services in .NET so it could either be a complex query that I just dump into a data table report or a less complex query with some counting and totaling done by the report. I just don't really know the best way to tackle this.
Since you don't know which colors are going to be the columns you should use the Matrix Control
You'll need to set up the query
SELECT
a.State,
b.ColorName,
COUNT(b.ColorID) ColorCount
FROM
alpha a
LEFT JOIN beta b
ON a.id = b.a_id
GROUP BY
a.State,
b.ColorName
Just drag state for the rows, color for the columns and ColorCount for the data (Count(ColorID) will display in the data field))
Note: The LEFT JOIN and Count(ColorID) instead of Count(*) are required if you want a 0 value to appear correctly.
If you did know the colors you could use PIVOT or the sum case technique
SELECT state SUM(CASE WHEN Color = 'RED' THEN 1 ELSE 0 END) as Red, ...

SQL Server - Group by, having and count in a mix

I have a database with a long list of records. Most of the columns have foreign keys to other tables.
Example:
ID SectorId BranchId
-- -------- --------
5 3 5
And then I will have a table with sectors, branches ect.
My issue:
I want to know how many records which has sector 1, 2, 3 ... n. So what I want is a group by Sector and then some count(*) which will tell me how many there is of each.
Expected output
So for instance, if I have 20 records the result might look like this:
SectorId Count
-------- -----
1 3
2 10
3 4
4 6
My attempts so far
I do not normally work a lot with databases and I have been trying to solve this for 1.5 hours. I have tried something like this:
SELECT COUNT(*)
FROM Records r
GROUP BY r.Sector
WHERE r.Date BETWEEN '2011-01-01' AND '2011-12-31'
But... errors and problems all over!
I would really appreciate some help. I do know this is probably very simple.
Thanks!
The sequence of your query is not correct; it should be like this: -
SELECT COUNT(*)
FROM Records r
WHERE r.Date BETWEEN '2011-01-01' AND '2011-12-31'
GROUP BY r.Sector
The output will be only counts i.e.
count
-----
3
10
4
6
If you want to fetch both sector and count then you need to modify the query a little
SELECT r.Sector, COUNT(*) as Count
FROM Records r
WHERE r.Date BETWEEN '2011-01-01' AND '2011-12-31'
GROUP BY r.Sector
The output will be like this: -
Sector Count
------ -----
1 3
2 10
3 4
3 6
Your query was partially right,But it needs some modification.
If I write this way:-
SELECT r.SectorID,COUNT(*) AS count
FROM Records r
WHERE r.Date BETWEEN '2011-01-01' AND '2011-12-31'
GROUP BY r.SectorID
Then output will be:-
SectorID Count
1 3
2 10
3 4
4 6

Resources