我正在进行查询以获得这些结果:
Concept | Variety 1 | Variety 2 | Variety 3
-------- | ---------- | --------- | ---------
Stage 1 | 125.23 | 142.32 | 154.00
State 2 | 100.00 | 100.00 | 100.00
我有2个DB来获取这些结果,这个查询给了我这个结果
查询:
SELECT A.Etapa as CEtapa
, Sum(P.Import) + Sum(P.HExtras) + Sum(P.Importunidades) as Total
FROM Percepciones as P
, [\SYS21\Camel\COSTOS.MDB].Lotes as L
, [\SYS21\Camel\COSTOS.MDB].Actividades as A
WHERE P.Apl2__ = L.Numero
AND P.Apl3__ = A.Numero
GROUP BY A.Etapa
ORDER BY A.Etapa
结果:
Concept | Variety 1
-------- | ----------
Stage 1 | 125.23
State 2 | 100.00
问题是我有N个品种,我需要查询来做到这一点,我使用.NET来显示这些结果。所以我想,“为什么不创建一个循环来添加各种变化。”但是,我遇到的问题是他们没有按阶段计算,这是我的测试查询:
SELECT A.Etapa as CEtapa
,(SELECT Total
FROM (SELECT Sum(P.Import) + Sum(P.HExtras) + Sum(P.Importunidades) as Total
FROM Percepciones as P
, [\SYS21\Camel\COSTOS.MDB].Lotes as L
, [\SYS21\Camel\COSTOS.MDB].Actividades as A
WHERE L.Numero = P.Apl2__
AND Variedad = L.Variedad
AND P.Apl3__ = A.Numero
)
) as Variedad1
FROM Percepciones as P
, [\SYS21\Camel\COSTOS.MDB].Lotes as L
, [\SYS21\Camel\COSTOS.MDB].Actividades as A
WHERE P.Apl2__ = L.Numero
AND P.Apl3__ = A.Numero
GROUP BY A.Etapa
我将循环使用.Net连接将是:
SELECT Total
FROM (SELECT Sum(P.Import) + Sum(P.HExtras) + Sum(P.Importunidades) as Total
FROM Percepciones as P
, [\SYS21\Camel\COSTOS.MDB].Lotes as L
, [\SYS21\Camel\COSTOS.MDB].Actividades as A
WHERE L.Numero = P.Apl2__
AND Variedad = L.Variedad
AND P.Apl3__ = A.Numero
)
) as Variedad1
可悲的是,这给了我在每个阶段的相同结果,因为我没有比较WHERE子句上的阶段,因为我不知道如何在子查询的主查询中使用阶段。
任何想法都将不胜感激。
答案 0 :(得分:1)
考虑MS Access SQL的唯一crosstab query,它围绕聚合TRANSFORM
查询包装PIVOT
和GROUP BY
子句,以动态地跨分组聚合聚合。
以下 Etapa 分组,以及 Variedad 聚合您计算的总计字段。请注意任何查询结果集中N = 255列的访问限制。此外,下面使用显式连接INNER JOIN
(ANSI '92标准25年),而不是使用由WHERE
子句连接的逗号分隔表的隐式连接。对于多个连接,Access SQL确实需要括号配对。
TRANSFORM Sum(P.Import) + Sum(P.HExtras) + Sum(P.Importunidades) as Total
SELECT A.Etapa as CEtapa
FROM (Percepciones as P
INNER JOIN [\SYS21\Camel\COSTOS.MDB].Lotes as L
ON P.[Apl2__] = L.[Numero])
INNER JOIN [\SYS21\Camel\COSTOS.MDB].Actividades as A
ON P.[Apl2__] = A.[Numero]
GROUP BY A.Etapa
PIVOT L.Variedad
如果您想限制列{}添加IN
到<{1}}:
PIVOT