I am using sql server 2008.i have one table which contains two columns.one is movie name and other one is rating.my table structure like that:
MovieName | Rating
ABC | 3
XYZ | 2
DEF | 1
i used following statement to display my table records.
Select * from tablename
what i want means instead of display the rating as numbers it should display, good for rating 3,better for rating 2 and worst for rating 1.
i.e)
i want like this
MovieName | Rating
ABC | Good
XYZ | Better
DEF | Worst
can anyone tell me how to display like this using sql statement??
SELECT MovieName,
CASE WHEN Rating = 1 THEN 'Worst'
CASE WHEN Rating = 2 THEN 'Better'
CASE WHEN Rating = 3 THEN 'Good' END AS Rating
FROM tablename
The better solution would be to have one more table with the ratings and join the 2 tables to display the result:
SELECT a.MovieName, b.Description AS Rating
FROM movies a JOIN ratings b on a.Rating = b.Rating
You can use CASE to map on the fly:
SELECT MovieName,
CASE Rating
WHEN 3 then 'Good'
WHEN 2 then 'Better'
WHEN 1 then 'Worst'
END AS Rating
FROM TableName
Preferably however, you should make use of a Lookup table and then the Rating column of TableName can be foreign keyed and then joined to this table to retrieve the Rating. This will have the benefit of enforcing referential integrity, and will also allow the rating names to be changed (or made e.g. cross language friendly) without hard coding into the code.
Well, in case you have just these 3 ratings, a fast and simple solution would be:
SELECT MovieName,
CASE rating
WHEN 3 then 'Good'
WHEN 2 then 'Better'
WHEN 1 THEN 'Worst'
from table
But if you intend to create more ratings I recommend creating another table (lookup table) which holds the rating names.
Ratings
Rating RatingName
1 Worst
2 Better
3 Good
4 Supercool
When you have this set up, you could do this operation much easier.
SELECT m.MovieName, r.RatingName
FROM movies m join ratings r on m.rating = r.rating
This will allow you to insert more rating "types" and you won't have to change the query (my first query) and add case situations for the aditional ratings. After adding more rating types and movies with other ratings, they will appear automatically in your results.
Related
I have a column in my SQL table. The value stored in this column is integer values for example 1,2,3,4,8 etc. Each value represents something else, such as 1=volvo, 2=BMW, 3=Ford etc. Is there a way to run a query where the results is translated from binary to text?
Current query:
SELECT *
FROM table carModel
Result:
1, green, hatchback
Desired result:
Volvo, green, hatchback
One solution is as follow:
Your table carModel lets say it has the following results:
id
color
model
1
green
Volvo
2
red
BMW
3
purple
Mercedes-benz
One more table called carTypes
id
model_id
type
1
1
Sedan
2
2
Coupe
3
3
Hatchback
In carTypes model_id is pointing to carModel id
And the very very simple INNER JOIN will do the job.
SELECT `CM`.`model`, `CM`.`color`, `CT`.`type`,
FROM `carModel` as `CM`
INNER JOIN `carTypes` as `CT` ON `CT`.`model_id ` = `CM`.`id`;
... as I wrote that is very simple example. You will probably need to read about how to link two tables, about Foreign key, how to create lookup and also not in last but how to populate in order to get right data. Of course if you don't know that already.
And keep in mind such a query like above will return you all data. Perhaps, you need to add WHERE clause in order to have more narrowed results.
Hope that helps you at least a bit.
If you don't have the mapping table, you can create one using with clause statement as below -
with car_model_map as (select 1 as model_id, 'volvo' as model_name
union
select 2, 'BMW'
union
select 3, 'Ford')
SELECT cm.model_name, ca.color, ca.model_type
FROM carModel ca join car_model_map cm on ca.model_id = cm.model_id
Use a CASE expression:
SELECT CASE MODEL_ID
WHEN 1 THEN 'Volvo'
WHEN 2 THEN 'BMW'
WHEN 3 THEN 'Ford'
ELSE 'I don''t know'
END AS MODEL_NAME,
COLOR,
BODY_STYLE
FROM carModel
I assume that the CarModel table includes the colums brandId, color, modelName
Create a table named "Brands" with Id column and brandName and Insert the brands in this table.
Then the below query should work:
SELECT b.brandName, cm.Color, cm.modelName
FROM carModel cm LEFT JOIN Brands b ON cm.brandId = b.Id
I am trying to create a table that has columns called user_id and top5_foods (binary column). I currently have two tables, one has all of the user_ids and the foods associated with those user_ids and one table that only contains the top5 foods according to a type of calculation to select the top5 foods.
The table that I am trying to create if to have the column of the user_id and if at least one of their favorite foods is in the top_5_food table, put the value of the top5_foods as 1 and if not, 0.
Something like the following:
user_id top5_foods
----------------------
34223 1
43225 0
34323 1
I have tried to use the CASE command but it just duplicated the user_ids and mark 1 or 0 whenever it finds a food that is in the top_5_foods table. But I don't want it to duplicate. Could you please help ?
Thank you very much
If I understand correctly, a left join and aggregation:
select uf.user_id,
(count(t.food_id) > 0) as top5_foods
from user_foods uf left join
top5_foods t
on uf.food_id = t.food_id
group by uf.user_id;
I am writing a SQL statement for Oracle where there is a one to many relationship between two tables. The table Person has a foreign key to table Purchase which has a Purchase Description field.
I need to write a SELECT query that will take all the purchase records/rows and append them to each other like so
Person Table
PersonID PersonName
1 John
Purchases Table
PurchaseId (PK), PersonID(FK), PurchaseDescription
1 1 Book
2 1 Clothes
3 1 Bag
4 1 Dinner
So the output of the query would look like this
Output = 1, Book:Bag:Clothes:Dinner
The output will be one row from the one to many relationship where there are separate records for book, bag, clothes, and dinner.
Any help is appreciated. Thanks
to do this use a function called LISTAGG, like this
SELECT 'Output = '||CAST(P.PersonID AS VARCHAR(100)), LISTAGG(Pur.PurchaseDescription, ':')
FROM Person P
LEFT JOIN Purchase Pur ON P.PersonID = Pur.PersonID
GROUP BY P.PersonID
for example :
I have a table with student ID and student grades
-----------------------
ID | grades
-----------------------
1 | 80
2 | 28
-----------------------
I want to get 0 when I query about ID = 3
can I do that ?
like select grades from student where id = 3 .
I want to get 0 because ID is not in the table
Run a select command with the reserved function called count:
select count(*) from STUDENT.GRADES where ID=3
It should be just like that.
Maybe this will do what you want:
SELECT ID, MAX(Grades)
FROM (SELECT ID, Grade FROM Students WHERE ID = 3
UNION
VALUES (3, 0) -- Not certain of syntax here
)
GROUP BY ID
The basic idea is that students present in the table will have two rows and the MAX will pick their proper grade (assuming that there are no circumstances where the grade is coded as a negative value). Students that are not represented will have just the one row with a grade of 0. The repeated 3 is the ID of the student being sought.
Have fun chasing down the full syntax. I started at Queries in the DB2 9.7 Information Centre, but ran out of patience before I got a good answer — and I don't have DB2 to experiment on. You might need to write SELECT ID, Grades FROM VALUES (3, 0), or there might be some other magical incantation that does the job. You could probably use SELECT 3 AS ID, 0 AS Grades FROM SYSIBM.SYSTABLES WHERE TABID = 1, but that's a clumsy expression.
I've kept with the column name Grades (plural) even though it looks like it contains one grade. It is depressing how often people ask questions about anonymous tables.
Goal is to replace a integer value that is returned in a SQL query with the char value that the number represents. For example:
A table attribute labeled ‘Sport’ is defined as a integer value between 1-4. 1 = Basketball, 2 = Hockey, etc. Below is the database table and then the desired output.
Database Table:
Player Team Sport
--------------------------
Bob Blue 1
Roy Red 3
Sarah Pink 4
Desired Outputs:
Player Team Sport
------------------------------
Bob Blue Basketball
Roy Red Soccer
Sarah Pink Kickball
What is best practice to translate these integer values for String values? Use SQL to translate the values prior to passing to program? Use scripting language to change the value within the program? Change database design?
The database should hold the values and you should perform a join to another table which has that data in it.
So you should have a table which has say a list of people
ID Name FavSport
1 Alex 4
2 Gnats 2
And then another table which has a list of the sports
ID Sport
1 Basketball
2 Football
3 Soccer
4 Kickball
Then you would do a join between these tables
select people.name, sports.sport
from people, sports
where people.favsport = sports.ID
which would give you back
Name Sport
Alex Kickball
Gnat Football
You could also use a case statement eg. just using the people table from above you could write something like
select name,
case
when favsport = 1 then 'Basketball'
when favsport = 2 then 'Football'
when favsport = 3 then 'Soccer'
else 'Kickball'
end as "Sport"
from people
But that is certainly not best practice.
MySQL has a CASE statement. The following works in SQL Server:
SELECT
CASE MyColumnName
WHEN 1 THEN 'First'
WHEN 2 THEN 'Second'
WHEN 3 THEN 'Third'
ELSE 'Other'
END
In oracle you can use the DECODE function which would provide a solution where the design of the database is beyond your control.
Directly from the oracle documentation:
Example: This example decodes the value warehouse_id. If warehouse_id is 1, then the function returns 'Southlake'; if warehouse_id is 2, then it returns 'San Francisco'; and so forth. If warehouse_id is not 1, 2, 3, or 4, then the function returns 'Non domestic'.
SELECT product_id,
DECODE (warehouse_id, 1, 'Southlake',
2, 'San Francisco',
3, 'New Jersey',
4, 'Seattle',
'Non domestic') "Location"
FROM inventories
WHERE product_id < 1775
ORDER BY product_id, "Location";
The CASE expression could help. However, it may be even faster to have a small table with an int primary key and a name string such as
1 baseball
2 football
etc, and JOIN it appropriately in the query.
Do you think it would be helpful to store these relationships between integers and strings in the database itself? As long as you have to store these relationships, it makes sense to store it close to your data (in the database) instead of in your code where it can get lost. If you use this solution, this would make the integer a foreign key to values in another table. You store integers in another table, say sports, with sport_id and sport, and join them as part of your query.
Instead of SELECT * FROM my_table you would SELECT * from my_table and use the appropriate join. If not every row in your main column has a corresponding sport, you could use a left join, otherwise selecting from both tables and using = in the where clause is probably sufficient.
definitely have the DB hold the string values. I am not a DB expert by any means, but I would recommend that you create a table that holds the strings and their corresponding integer values. From there, you can define a relationship between the two tables and then do a JOIN in the select to pull the string version of the integer.
tblSport Columns
------------
SportID int (PK, eg. 12)
SportName varchar (eg. "Tennis")
tblFriend Columns
------------
FriendID int (PK)
FriendName (eg. "Joe")
LikesSportID (eg. 12)
In this example, you can get the following result from the query below:
SELECT FriendName, SportName
FROM tblFriend
INNER JOIN tblSport
ON tblFriend.LikesSportID = tblSport.SportID
Man, it's late - I hope I got that right. by the way, you should read up on the different types of Joins - this is the simplest example of one.