SQL查询修剪一列?

时间:2016-01-13 13:33:50

标签: sql sql-server trim

我使用以下查询来填充一些数据。从列“查询表达式”有一种方法可以删除N'Domain \

左侧的任何文本

基本上我只想在“查询表达式”栏目中看到N'Domain \之后的文字。不知道该怎么做。

SELECT
  v_DeploymentSummary.SoftwareName,
  v_DeploymentSummary.CollectionName,
  v_CollectionRuleQuery.QueryExpression
FROM
v_DeploymentSummary
INNER JOIN v_CollectionRuleQuery
ON v_DeploymentSummary.CollectionID = v_CollectionRuleQuery.CollectionID

3 个答案:

答案 0 :(得分:1)

至少对于SQL Server:

SUBSTRING([v_CollectionRuleQuery.QueryExpression], CHARINDEX('N''Domain\', [v_CollectionRuleQuery.QueryExpression]) + 9, LEN([v_CollectionRuleQuery.QueryExpression])

试一试。

我不明白你是否想在你的字符串中包含N'Domain \,如果是这样的话只需删除+9。

根据我的理解,你想要这样的东西:

SELECT
  v_DeploymentSummary.SoftwareName,
  v_DeploymentSummary.CollectionName,
  SUBSTRING([v_CollectionRuleQuery.QueryExpression], CHARINDEX('N''Domain\', [v_CollectionRuleQuery.QueryExpression]) + 9, LEN([v_CollectionRuleQuery.QueryExpression])
FROM
v_DeploymentSummary
INNER JOIN v_CollectionRuleQuery
ON v_DeploymentSummary.CollectionID = v_CollectionRuleQuery.CollectionID

答案 1 :(得分:1)

在SQL Server中,您可以使用stuff()来实现此目的:

SELECT ds.SoftwareName, ds.CollectionName,
       STUFF(crq.QueryExpression, 1,
             CHARINDEX('Domain\', rq.QueryExpression) + LEN('Domain\') - 1,
             '')
FROM v_DeploymentSummary ds INNER JOIN
     v_CollectionRuleQuery crq
     ON ds.CollectionID = crq.CollectionID;

请注意,使用表别名可以使查询更容易编写和读取。

答案 2 :(得分:1)

试试这个,如果没有文字N'域,它不会更改QueryExpression的值,也不要求N' Domain是第一个文本:

SELECT `us`.`userSurveyID`, 
    // More columns from main query `us`
    `firstAccess`.`timestamp` AS `dateFirstAccess`
FROM `user_surveys` AS `us`
LEFT JOIN (
    SELECT `user_survey_status_entries`.`userSurveyID`, 
            MIN(timestamp) AS `timestamp` 
    FROM `user_survey_status_entries` 
    WHERE (status = 20) 
    GROUP BY `userSurveyID`
) AS `firstAccess` ON us.userSurveyID = firstAccess.userSurveyID 
WHERE (us.surveyID = '10')

示例:

SELECT
  ds.SoftwareName,
  ds.CollectionName,
  crq.QueryExpression
  STUFF(crq.QueryExpression, 1, charindex('N''Domain\', 
    REPLICATE('w', LEN('N''Domain\')-1) + crq.QueryExpression), '')
FROM
  v_DeploymentSummary ds
JOIN 
  v_CollectionRuleQuery crq
ON ds.CollectionID = crq.CollectionID

结果:

SELECT 
  STUFF(x, 1, charindex('N''Domain\', 
    replicate('w', LEN('N''Domain\')-1) + x), '')
FROM (values('N''Domain\xxx'),('N''Doma'),('xxN''Domain\yyy')) x(x)