postgresql SQL SELECT FROM ... AS 带有数据类型说明符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/187281/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-19 23:35:47  来源:igfitidea点击:

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

sqlpostgresql

提问by VolkA

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

我在 Postgresql 上的 SQL 查询有问题。这个 select 子句是数据库讲座中的一个例子:

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.

问题是第 2 行的 Marketshare 列。 StudentsPerCourse 和 StudentCount 都是整数类型。

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?

在我的 Postgresql 数据库上使用它时,Marketshare 列被评估为 int 类型,而我在这里需要一个浮点数/数字。我没有找到通过在 SELECT 子句上搜索 Postgresql 文档或通过谷歌搜索来指定数据类型的任何方法。是否有(最好是标准 SQL)方式来指定列类型,或者我在这里遗漏了什么?

采纳答案by Joel Coehoorn

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

CAST() 作为十进制/浮点数/实数/双精度/等类型的源列之一或两者。