SQLite: Select all Names of given Colors - sqlite

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.

Related

INNER JOIN Number Range Lookup on VARCHAR

So im wondering if its possible for SQLite to understand number ranges.
I want to be able to have a range such as "25-30" and lookup "27" to see if it falls within that range.
The issue is that the range will contain some text beforehand such as "Alice 25-30"
An example of what Id be looking to achieve can be seen in Table3 of this link:
https://dbfiddle.uk/?rdbms=sqlite_3.27&fiddle=483f62c5fbf13998659cd5f7ebbb3ce9
More than happy for solutions that can break the string at the first number, but still keep the number so
Alice | 25-30
Not
Alice | 5-30 (ive seen this suggested before :D)
To actually create Table 3 ill be using either INNER or LEFT OUTER JOIN not just Re-creating the table but was speedier to do this
Thanks in advance.
You can do it with a join of the 2 tables like this:
INSERT INTO Table3 (`ID`, `Age`,'Age Range')
SELECT t1.ID, t1.Age, t2.`Age Range`
FROM Table1 t1 INNER JOIN Table2 t2
ON t1.Age + 0 BETWEEN `Age Range` + 0
AND SUBSTR(`Age Range`, INSTR(`Age Range`, '-') + 1) + 0
SQLite performs implicit conversions of strings to numbers when they are used in expressions with numeric operations like +0, so what the query does is to compare Age to the 1st and the 2nd part of Age Range numerically.
Note that + 0 would not be needed in ON t1.Age + 0 BETWEEN if you had defined Age as REAL which makes more sense.
Change the INNER join to LEFT join if you want the row from Table1 inserted to Table3 even if there is no matching Age Range.
See the demo.
Results:
ID
Age
Age Range
1
30
25-30
2
40.5
31-45

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

Making an Update Query to Count Occurrences

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

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

ASP.NET - Data Grid and Drop Down list

I am working on a web page that has a data grid and have a need to do
the following:
Have a column that is a drop down when the grid loads (no need to click edit)
This column is bound to a column from the data query (everything up
to this point works fine)
I know need to add more values to this drop down from another
dataset (so the user can change the value if required)
These values come from a query to another table in the database. The
values will be same for all the rows in the table, these values are
based on a master key for the complete webpage.
As an example:
table 1 has:
Mangoes $12
Apricots $13
Peaches $14
This is on the grid.
The other table has:
Prices
12
13
14
15
16
I want these values from the prices table to appear in the drop down
for table 1 in the data grid, with the current values as the selected
item.
Any ideas will help. Thanks for the help.
As far as I know,
U should better change ur table design.
If ur fruit table is concern with price id, then u can easily select the item from dropdown with current value in fruit table.
Fruit
PriceId
PriceId
Price
------------------------ --------------------
Mangoes
1
<--------------------->
1
12
Apricots
2
<--------------------->
2
13
Peaches
3
<--------------------->
3
14
then it is easier to list all price in dropdown list
and also easier to choose selected price based on PriceId from Fruit table.
Sound like little confuse? let me know, if anything u want?
Hope it works!

Resources