3

我有一个包含以下列的表:

          Cost     Rate

          Repair   12
          Repair   223
          Wear     1000    
          Wear     666
          Fuel     500
          Repair   600
          Fuel     450
          Wear     400

我希望这些数据作为列(修复、磨损、燃料)为:

         Repair    Wear   Fuel
           825     2066    950

我如何使用 MS Access Query 做到这一点?

4

5 回答 5

5

虽然有一个非常笨拙的传统 SQL 解决方案,但阅读此页面提醒我,MS Access 有一个TRANSFORM ... PIVOT语句,您可能应该查看并使用它来执行此操作。

我不能确定,但​​它应该看起来像:

TRANSFORM Sum([Items].[Rate]) AS SumOfRate 
SELECT [Items].[Costs] 
FROM Items 
GROUP BY [Items].[Costs] 
PIVOT Format([Items].[Costs]);

它可以变得比这更漂亮。例如

PIVOT Format([Items].[month],"mmm") In ("Jan","Feb",...,"Nov","Dec");
于 2009-06-27T07:15:01.917 回答
3

未经测试但

SELECT
(SELECT  sum(rate)  from mytable where cost = 'Repair') AS Repair ,
(SELECT  sum(rate) from mytable where cost = 'Wear') AS Wear,
(SELECT  sum(rate) from mytable wherecost = 'Fuel') AS Fuel
于 2009-06-27T06:54:07.060 回答
2

您可以使用交叉表查询来执行此操作。Access Queries 窗口中有一个向导将引导您完成创建一个向导。只需单击 New Query 按钮并选择 Crosstab Query Wizard。

于 2009-07-13T04:10:07.330 回答
2

你可以使用这个查询

select 
sum(select rate from yourtable where cost = 'Repair') "Repair", 
sum(select rate from yourtable where cost = 'Wear') "Wear", 
sum(select rate from yourtable where cost = 'Fuel') "Fuel" 
from dual

如果您使用的是 Oracle

否则,如果有任何其他数据库引擎,您可以在此之前快速声明

create table dual (x char)

insert into dual values "x"
于 2009-06-27T06:54:53.923 回答
1

这将获得您需要的数据:

select cost, sum(rate)

from mytable

group by cost

然后你可以以任何你喜欢的方式呈现它。

于 2009-06-27T06:44:22.913 回答