简体   繁体   English

SQL枢轴-交叉表和多列

[英]SQL pivot - cross tab and multiple columns

I've got 2 crosstab queries that both work, but I'd like to combine them together. 我有两个交叉表查询都可以,但是我想将它们组合在一起。

The first shows the total time that various vehicles were used for at each base: 第一个显示每个基地使用各种车辆的总时间:

TRANSFORM Sum(Cdbl(Nz(M.dtTripTime, 0))) AS SheetTime

SELECT M.lngVehicleID
    ,Sum(Cdbl(Nz(M.dtTripTime, 0))) AS Total
FROM tblSheets M
INNER JOIN Bases B ON M.lngBaseID = B.BaseID
GROUP BY M.lngVehicleID
PIVOT B.BaseName IN (
        'Alpha'
        ,'Bravo'
        ,'Charlie'
        );

The second shows the number of trips that each vehicle did at various bases: 第二个显示了每辆车在不同地点的出行次数:

TRANSFORM Count(M.lngSheetID) AS SheetCount

SELECT M.lngVehicleID
    ,Sum(Cdbl(Nz(M.dtTripTime, 0))) AS Total
FROM tblSheets M
INNER JOIN Bases B ON M.lngBaseID = B.BaseID
GROUP BY M.lngVehicleID
PIVOT B.BaseName IN (
        'Alpha'
        ,'Bravo'
        ,'Charlie'
        );

What I'd ideally like is to generate one crosstab that shows both the combined time and the number of trips for each vehicle at the various bases. 我理想的情况是生成一个交叉表,该交叉表同时显示各个基准点的每辆车的综合时间和出行次数。 Is this possible? 这可能吗? The above queries maxed out my very limited abilities on SQL! 以上查询使我在SQL上的能力非常有限!

In Access, a crosstab allows only one value, one column variable and several row variables, but you could make a third query based on the two you have above, keying on lngVehicleID , along the lines of the following--anything else I think would require a VBA solution, but is rather unnecessary. 在Access中,交叉表仅允许一个值,一个列变量和几个行变量,但是您可以基于上面的两个查询进行第三个查询,键入lngVehicleID ,如下所示-我想其他任何方式需要VBA解决方案,但这是不必要的。

I assume your crosstabs are saved, named, respectively, and inspiredly, crosstab1 and crosstab2 . 我假设您的交叉表已保存,分别命名,并且启发性地命名为crosstab1crosstab2

[not tested] [未测试]

Select * from crosstab1
inner join crosstab2 on crosstab1.lngVehicleID=crosstab1.lngVehicleID
order by crosstab1.lngVehicleID

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM