Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL SELECT FROM ... AS with data type specifier?

Tags:

sql

postgresql

I have a problem with an SQL query on Postgresql. This select clause is an example from a lecture on databases:

1 select t.CourseNr, t.StudentsPerCourse, g.StudentCount, 
2        t.StudentsPerCourse/g.StudentCount as Marketshare
3 from (select CourseNr, count(*) as StudentsPerCourse
4       from taking
5       group by CourseNr) t,
6      (select count(*) as StudentCount
7       from Students) g;

The problem is the Marketshare column in line 2. Both StudentsPerCourse and StudentCount are of type integer.

When using this on my Postgresql database, the Marketshare column is evaluated as an int type, while i would need a float/numeric here. I didn't find any way to specify the data type by searching the Postgresql Documentation on SELECT clauses nor by googling. Is there a (preferably standard SQL) way to specify the column type or am I missing something here?

like image 932
VolkA Avatar asked Oct 09 '08 13:10

VolkA


People also ask

How do I SELECT data type in SQL?

You can get the MySQL table columns data type with the help of “information_schema. columns”. SELECT DATA_TYPE from INFORMATION_SCHEMA. COLUMNS where table_schema = 'yourDatabaseName' and table_name = 'yourTableName'.

What is %% in SQL query?

The LIKE operator is used in a WHERE clause to search for a specified pattern in a column. There are two wildcards often used in conjunction with the LIKE operator: The percent sign (%) represents zero, one, or multiple characters.

What is the use of as keyword with SELECT statement?

SQL AS keyword is used to give an alias to table or column names in the queries. In this way, we can increase the readability and understandability of the query and column headings in the result set.

Can we use SELECT * with group by?

Cannot use an aggregate or a subquery in an expression used for the group by list of a GROUP BY clause. The original idea was to create the table in beginning of the query, so the (SELECT * FROM #TBL) could be used on the query itself, instead of defining the names on each GROUP BY.


1 Answers

CAST() one or both of the source columns as a decimal/float/real/double/etc type.

like image 138
Joel Coehoorn Avatar answered Oct 24 '22 07:10

Joel Coehoorn