SQL选择多项作为值= 1,2和3的值

时间:2015-10-29 10:57:36

标签: sql sql-server

所以我想选择一些用逗号分隔的值到注释字段中,其中值等于某些匹配。

以下是我的表格。

[dbo].[ValuationDetail](
[ValuationDetailId] [int] IDENTITY(1,1) NOT NULL,
[ValuationId] [int] NOT NULL,
[TagName] [varchar](100) NOT NULL,
[TagValue] [varchar](max) NULL,
[Mod] [varchar](50) NOT NULL,
[IncludePdf] [bit] NOT NULL,
[IsBinary] [bit] NOT NULL,

enter image description here

我想做类似的事情。

SELECT 
  ValuationId,
  TagValue as Comment WHERE TagName = 'Sale_8_township', 'Sale_8_portion', 'Sale_8_erf'
WHERE ValuationId = 21702

结果

评论= ST HELENA BAY,0,1719

如果您需要更多信息,请与我们联系。

3 个答案:

答案 0 :(得分:0)

你需要类似MySQL的GROUP_CONCAT

SELECT 
  ValuationId,
  GROUP_CONCAT(TagValue) as Comment 
FROM table
WHERE TagName IN (Tag1, Tag2, Tag3)
AND ValuationId = 123
GROUB BY ValuationId

如果您不想在SQL Server中创建新功能,可以使用STUFF内置函数进行解决:

STUFF(
         (SELECT ', ' + TagValue
          FROM table
          WHERE ValuationId = outer. ValuationId
          FOR XML PATH (''))
          , 1, 1, '')  AS Comment

答案 1 :(得分:0)

Coalesce帮我连接存储在临时表中的字符串。

SELECT @Comment = COALESCE(@Comment + ',','') + TagValue FROM #TempComment
CREATE TABLE #TempComment (id int, TagValue varchar(500))

INSERT INTO #TempComment
        SELECT
            CASE
                WHEN TagName = @saleErf THEN  1
                WHEN  TagName = @salePortion THEN 2
                WHEN  TagName = @saleTownship THEN 3
                WHEN  TagName = @salePrice THEN 4
                WHEN  TagName = @saleDate THEN 5
                WHEN  TagName = @saleOverall THEN 6
            END,
            TagValue
        FROM ValuationDetail
        WHERE TagName IN (@saleErf,@salePortion,@saleTownship, @salePrice, @saleDate, @saleOverall) AND ValuationId = @ValuationId

SELECT @Comment = COALESCE(@Comment + ',','') + TagValue FROM #TempComment ORDER BY Id

答案 2 :(得分:-1)

Liketemp表格一起使用。

CREATE TABLE patterns (
  pattern VARCHAR(20) --- max varchar as your need
);

INSERT INTO patterns VALUES ('Tag1%'), ('Tag2%'), ('Tag3%');

SELECT vt.* FROM ValuationDetail vt JOIN patterns p ON (vt.col LIKE p.pattern);