从多个Access-SQL行到一行

时间:2012-11-15 14:37:57

标签: sql vba ms-access concatenation

这是对我上一个问题Concatenate 2 rows in a complex SQL query的跟进。

以下是我从这个问题中得到的:

PARAMETERS [CurrAxe] TEXT ( 255 ), [CurrOTP] TEXT ( 255 ), [CurrClient] TEXT (
255 ), [StartDate] DATETIME, [EndDate] DATETIME;

SELECT q.Projet, *
FROM   (faitssaillants f
LEFT JOIN employes e
ON f.utilisateur = e.cip)
INNER JOIN (
SELECT s1.otp,
     [s1].[valeur] & "," & [s2].[valeur] AS Projet
FROM   (
  SELECT otp, valeur
  FROM   tb_sommaire
  WHERE  [variable] = 'TitreMandat') AS s1
INNER JOIN (
   SELECT otp, valeur
   FROM   tb_sommaire 
   WHERE  [variable] = 'NomInstallation') AS s2
ON s1.otp = s2.otp) q
ON f.otp = q.otp
WHERE f.otp  = [currotp] 
AND f.client LIKE [currclient] 
AND f.axe LIKE [curraxe] 
AND Datevalue([dateinsertion]) 
    Between [startdate] And [enddate] 
ORDER  BY f.dateinsertion DESC; 

如果我想用[variable] ='something else'而不是'TitreMandat'或'NomInstallation'添加另一行(让我们将其命名为s3)怎么办?是否有可能将所有tb_sommaire.variable作为字段并将tb_sommaire.valeur作为值来获取tb_sommaire.otp = faitssaillants.otp?它也许可以解决我未来的问题。

1 个答案:

答案 0 :(得分:0)

我会在包括交叉表在内的两个查询中执行您的第一个解决方案。第一个名为qry1 SQL的查询:

SELECT 
  f.index, f.project, f.axe, f.client, f.otp, s.variable, s.valeur, 
  f.FaitSaillant, f.dateInsertion, f.Utilisateur, e.empname
FROM 
  (FaitsSaillants AS f INNER JOIN 
  tb_SOMMAIRE AS s ON 
  f.otp = s.otp) LEFT JOIN 
  employes AS e ON 
  f.Utilisateur = e.cip;

您可以将WHERE条件添加到此查询中。

第二个查询,交叉表一:

TRANSFORM First(qry1.valeur) AS FirstOfvaleur
SELECT qry1.index, qry1.project, qry1.axe, qry1.client, qry1.otp
FROM qry1
GROUP BY qry1.index, qry1.project, qry1.axe, qry1.client, qry1.otp
PIVOT qry1.variable;

然后您可以为每个valeur

连接variable s