1

几天来,我一直在尝试 (grrr) 使用 MS Query 中的手动 SQL 语句窗口从连接 ODBC 的数据库中提取数据。我可以看到我想做的事情,但是我对语法很感兴趣(我很确定它是特定于 MS Query 的)。

问题是这样的:

我有四个表:waybill, waybill_item, rail_blrail_bl_item,它们之间包含有关通过运输设施处理的重量的信息,货物要么被运送到卡车(运单)或铁路(铁路)上。waybill和表分别包含卡车和铁路货物的rail_bl日期数据;而waybill_itemrail_bl_item包含有关这些物品重量的数据。

我想要一个表格,该表格将返回每天处理的总重量 - 铁路和卡车运输。IE

DATE | WEIGHT
date1, (truck_weight_for_date1+rail_weight_for_date1)
date2, (truck_weight_for_date2+rail_weight_for_date2)
date3, (truck_weight_for_date3+rail_weight_for_date3)
etc

通过执行查询,

SELECT waybill.creation_date, sum(waybill_item.weight)
FROM waybill
INNER JOIN waybill_item
ON waybill.id = waybill_item.waybill_id
WHERE waybill.creation_date > '01/01/2012'
GROUP BY waybill.creation_date
UNION
SELECT rail_bl.creation_date, sum(rail_bl_item.total_weight)
FROM rail_bl
INNER JOIN rail_bl_item
ON rail_bl.id = rail_bl_item.rail_bl_id
WHERE rail_bl.creation_date > '01/01/2012'
GROUP BY rail_bl.creation_date
ORDER BY waybill.creation_date DESC

我能够在单独的记录中获得包含给定日期的卡车总重量和给定日期的铁路总重量的两列结果,所以我的结果如下所示:

DATE | WEIGHT
date1, truck_weight_for_date1
date1, rail_weight_for_date1
date2, truck_weight_for_date2
date2, rail_weight_for_date2
date3, truck_weight_for_date3
date3, rail_weight_for_date3
etc

我遇到的问题是,我无法让 MS Query 接受将上述查询用作子查询,然后对每个日期的记录求和。即使尝试将我的查询作为子查询进行测试也不起作用。

例如,尝试

SELECT * FROM
(
SELECT waybill.creation_date, sum(waybill_item.weight)
FROM waybill
INNER JOIN waybill_item
ON waybill.id = waybill_item.waybill_id
WHERE waybill.creation_date > '01/01/2012'
GROUP BY waybill.creation_date
UNION
SELECT rail_bl.creation_date, sum(rail_bl_item.total_weight)
FROM rail_bl
INNER JOIN rail_bl_item
ON rail_bl.id = rail_bl_item.rail_bl_id
WHERE rail_bl.creation_date > '01/01/2012'
GROUP BY rail_bl.creation_date
)
ORDER BY waybill.creation_date DESC

返回“无法添加表 '('”错误。其他语法变体返回类似错误。

有谁知道 - 或者即使 - MS Query 能够执行这样的子查询?提前感谢您的帮助。

4

1 回答 1

0

为了将其用作子查询,您需要在两个地方使用别名。首先,列需要一个名称。其次,派生表需要一个名字:

select *
from (SELECT waybill.Creation_date, sum(waybil_item.weight) as Weight
      . . .
      union all
      . . .
     ) t
order by 1 desc

顺便说一句,你想要 UNION ALL 而不是 UNION。如果您碰巧在给定日期有相同的值,UNION 会消除它们。

于 2012-09-13T18:41:31.433 回答