简体   繁体   English

SQL:如何仅对列中的某些字符执行选择

[英]SQL:how to perform select only on some characters from a column

I wanted to know how to perform the SQL SELECT operation on only a particular range of characters. 我想知道如何仅对特定范围的字符执行SQL SELECT操作。 For example,I've got an SQL query: 例如,我有一个SQL查询:

SELECT date,score from feedback GROUP BY date

Now this date is of format yyyy/mm/dd . 现在,此日期的格式为yyyy/mm/dd

So I wanted to strip the days or cut out the days from it and make it yyyy/mm , thereby selecting only 0-7 characters from the date. 因此,我想删除日期或从中删除日期,并使其为yyyy/mm ,从而从日期中仅选择0-7个字符。

I've searched everywhere for the answer but could not find anything.Could I maybe do something like this? 我到处都在寻找答案,但找不到任何东西。我可以做这样的事情吗?

SELECT date(7),score from feedback GROUP BY date(7)

In MSQL you use LEFT other use substring 在MSQL中,您使用LEFT,其他使用子字符串

SELECT LEFT('abcdefg',2);
-- 
ab 

So in your case 所以你的情况

SELECT LEFT(date,7), score
FROM feedback
GROUP BY LEFT(date,7)

But again things will be much easier if you use a date field instead a text field. 但是同样,如果使用日期字段而不是文本字段,事情会容易得多。

Assuming that your date field is an actual date field (or even a datetime field) the following solution would work: 假设您的日期字段是实际日期字段(甚至是日期时间字段),则以下解决方案将起作用:

select left(convert(date ,getdate()),7) as Year_Month

Changing getdate() to your date field, it would look like: 更改getdate()你的date字段,它会看起来像:

select left(convert(date , feedback.date),7) as Year_Month

Both queries return the following: 这两个查询都返回以下内容:

2016-01

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM