SQL获取一行查询结果的值

时间:2017-10-12 09:19:52

标签: sql tsql

我有这个问题:

SELECT 
      R.ID
     ,O.DisplayName
     ,[Value]
FROM AA_V_PHR_CCD_ResultsXResults R 
INNER JOIN AA_V_PHR_CCD_ResultsObservationXLANGUAGES O
           ON R.IDResultObservation = O.ID  
WHERE IDResults = 149 AND O.IDLanguage = 2

所以这是此查询的结果:

ID  DisplayName Value
1604    HBsAg   0.140
1605    HBsAb   0.000
1606    HCV 0.020

如果有可能,我希望得到这个结果:

1604 HBsAg: 0.140 1605 HBsAb: 0.00 etc

可以这样做

3 个答案:

答案 0 :(得分:1)

You should use STUFF function as below:

SELECT STUFF(
            (
                SELECT ' '+CONVERT(VARCHAR(MAX), ID)+' '+DisplayName+' : '+CONVERT(NVARCHAR(MAX), Value)
                FROM <table_name> FOR XML PATH('')
            ), 1, 1, '') [data]; 

Output :

data
1604 HBsAg : 0.14 1605 HBsAb : 0.00 1606 HCV   : 0.02

答案 1 :(得分:0)

你可以试试这个:

    SELECT stuff(
                 (
                   SELECT cast(',' as varchar(max)) + R.ID || ' ' || O.DisplayName  || ' ' || [Value]
                     FROM AA_V_PHR_CCD_ResultsXResults R 
               INNER JOIN AA_V_PHR_CCD_ResultsObservationXLANGUAGES O
                       ON R.IDResultObservation = O.ID  
                    WHERE IDResults = 149 
                      AND O.IDLanguage = 2    for xml path('')
                 ), 
               1, 1, '') AS my_results
      FROM AA_V_PHR_CCD_ResultsXResults R 
INNER JOIN AA_V_PHR_CCD_ResultsObservationXLANGUAGES O
        ON R.IDResultObservation = O.ID  
     WHERE IDResults = 149 
       AND O.IDLanguage = 2

答案 2 :(得分:0)

This could solve the problem without using XML, if that helps

DECLARE @Temp NVARCHAR(MAX) = ''

SELECT @TEMP = CONCAT(@Temp, CAST(ID AS VARCHAR(4)), ' ', DisplayName, ' :', CAST(Value AS VARCHAR(5), ' ')
FROM Table

SELECT @Temp