我正在尝试从纽约市的帮助请求中的bigquery数据中选择一些行和列。我想选择五列 - 创建日期请求,提出请求的城市,收到请求的代理商等等。
首先,我设法选择了我想要的列:
conn <- dbConnect(SQLite(),'nyc311.db')
dbListFields(conn, "requests")
df<-dbGetQuery(conn, 'SELECT "Agency", "Created Date", "Complaint Type", "City", Descriptor FROM requests)
Agency Created Date Complaint Type City Descriptor
1 DOHMH 01/25/2016 02:11:12 AM Indoor Air Quality BRONX Chemical Vapors/Gases/Odors
2 NYPD 01/25/2016 02:08:08 AM Noise - Vehicle NEW YORK Car/Truck Horn
3 NYPD 01/25/2016 02:07:24 AM Noise - Street/Sidewalk NEW YORK Loud Talking
4 CHALL 01/25/2016 02:05:00 AM Opinion for the Mayor HOUSING
5 HRA 01/25/2016 02:01:46 AM Benefit Card Replacement Medicaid
6 NYPD 01/25/2016 01:54:56 AM Blocked Driveway CORONA No Access
如何从.db文件中选择以便我获得代理商= NYPD,City = Bronx和Queens;和创建日期= 2015年?我尝试了以下但是我遇到了语法错误。
df<-dbGetQuery(conn, 'SELECT "Agency", "Created Date", "Complaint Type", "City", Descriptor
FROM requests WHERE City IN ("BRONX", "QUEENS") AND Agency="NYPD"
AND YEAR(Created Date)=2015')
我是初学者所以我不清楚如何分配年份,因为创建日期以字符格式显示日期和时间,而不是整数。我还注意到代码运行除了YEAR(Created Date)=2015
答案 0 :(得分:0)
SQLite中没有YEAR()
函数(虽然MySQL有一个,因此你的困惑)。首先请注意,您将日期存储为文本,并且还以非ANSI格式mm/dd/yyyy
存储。为了比较每条记录的年份,您必须使用SQLite的字符串函数提取此信息。以下应该有效:
SUBSTR("Created Date", 7, 4)
请注意,您还需要将Created Date
列名称放在双引号中以转义空格。
以下是我将使用的实际查询:
SELECT "Agency",
"Created Date",
"Complaint Type",
"City",
"Descriptor"
FROM requests
WHERE City IN ('BRONX', 'QUEENS') AND
Agency = 'DOHMH' AND
SUBSTR("Created Date", 7, 4) = '2015' -- compare against the string '2015'
一些注释: SQL中的常规是对字符串数据使用单引号。您可以将所有列名称都放在双引号中,但只有在有空格,关键字等时才需要。
答案 1 :(得分:0)
我认为创建日期的语法错误 检查一下
'SELECT "Agency", "Created Date", "Complaint Type", "City", Descriptor
FROM requests WHERE City IN ("BRONX", "QUEENS") AND Agency="DOHMH"
AND YEAR("Created Date")=2015'