加入2个选择语句

时间:2016-01-14 07:23:05

标签: sql sql-server-2014

如何加入这两个select语句: 我尝试将@formateurs添加到第二个查询但它不起作用。

首先查询:

DECLARE @formateurs varchar(max)
SET @formateurs = ''

SELECT @formateurs = @formateurs + distinct(formateur) 
FROM onglet_forma_salles 
WHERE code = '0000001' 
ORDER BY Sort

SELECT @formateurs

第二次查询:

SELECT code, u_date, cardname, @formateurs
FROM session s
JOIN onglet_forma_salles ofs ON s.code = ofs.code
WHERE s.code = '0000001'
GROUP BY u_date

2 个答案:

答案 0 :(得分:2)

这应提供[formateurs]的独特列表(以逗号分隔)

SELECT
      g.code, g.u_date, g.cardname, fxp.formateurs
FROM (
      SELECT
            code
          , u_date
          , cardname
      FROM session s
            JOIN onglet_forma_salles ofs ON s.code = ofs.code
      WHERE s.code = '0000001'
      GROUP BY
            u_date
) AS g
      OUTER APPLY (
            SELECT
                  STUFF((
                        SELECT DISTINCT
                              ',' + formateur
                        FROM onglet_forma_salles
                        WHERE g.code = onglet_forma_salles.code
                        FOR xml PATH (''), TYPE
                  )
                  .value('.', 'NVARCHAR(MAX)')
                  , 1, 1, '')
      ) AS fxp (formateurs)

答案 1 :(得分:1)

第二个查询的正确语法如下: -

    DECLARE @formateurs varchar(max)
    SET @formateurs = ''

    SELECT s.code, u_date, cardname, @formateurs
    FROM session s JOIN onglet_forma_salles ofs 
    ON s.code = ofs.code
    WHERE s.code = '0000001'
    GROUP BY s.code, u_date, cardname