有意查询空白字段

时间:2014-03-17 15:24:30

标签: sql ms-access

我有一个包含下表的Microsoft Access数据库:

TableName: Parts
Cabinet ID - Number
Part ID - Number
PartClass - Number
Width - Number (double)
Length - Number (double)
Description - Text

我使用以下SQL查询来获取三个视图:

DoorPanels:
SELECT Parts.[Cabinet ID], Count(Parts.[Cabinet ID]) as Qty, Parts.Description as Name Parts.Width, Parts.Length 
FROM Parts
WHERE PartClass=13 GROUP BY Parts.[Cabinet ID], Parts.Description, Parts.Width, Parts.Length
ORDER BY Parts.[Cabinet ID]

DoorRails:
SELECT Parts.[Cabinet ID], Count(Parts.[Cabinet ID]) as Qty, Parts.Description as Name Parts.Width, Parts.Length 
FROM Parts
WHERE PartClass=14 GROUP BY Parts.[Cabinet ID], Parts.Description, Parts.Width, Parts.Length
ORDER BY Parts.[Cabinet ID]

DoorStiles:
SELECT Parts.[Cabinet ID], Count(Parts.[Cabinet ID]) as Qty, Parts.Description as Name Parts.Width, Parts.Length 
FROM Parts
WHERE PartClass=15 GROUP BY Parts.[Cabinet ID], Parts.Description, Parts.Width, Parts.Length
ORDER BY Parts.[Cabinet ID]

这给了我三个独立的视图,只包含我想要的部分。现在,我还有一张表:

TableName: Doors
Cabinet ID - Number
Door ID - Number
Width - Number (double)
Height - Number (double)

我还使用另一个查询为此创建视图:

SELECT Doors.[Cabinet ID], Count(Doors.[Door ID]) as Qty FROM Doors GROUP BY Doors.[Cabinet ID] ORDER BY Doors.[Cabinet ID]

所以,最后我想加入所有这些...但这是我有点失落的地方。根据我检索到的数据,我需要得到的结果是这样的结果:

Doors.[Cabinet ID]    Doors.Qty    DoorRails.*    DoorStiles.*  DoorPanels*
1                     2            [data]         [data]        [data]
                                   [data]         [data]        [data]
2                     3            [data]         [data]        [data]
                                   [data]         [data]        [data]
                                   [data]         [data]        [data]

现在,为了解释我在上面的结果中所说的内容,您可以看到,对于[Cabinet ID] 1,我的门数量为2,所以我需要2个记录来获取该门的部件。 [Cabinet ID] 2有3个门,所以我需要3个记录所有门部件。

现在,我知道这有点复杂,可能......好吧......不可能,但我已经在这方面工作了几天而没有想出任何东西。如果不可能的话,我很感谢这里的专家告诉我的。

仅供参考 - 我无法对数据库或结构进行任何更改,我所能做的就是针对它运行查询。

1 个答案:

答案 0 :(得分:1)

我认为最简单的方法是通过笛卡尔连接到一个表,该表只有一行,单个字段从1增加到你需要的最大门数。例如,

Counter.Num
-----------
1
2
3

如果您甚至无法创建供自己使用的本地表,则可以使用UNION查询来模拟上述表。 Access有一些limitations here,因此即使您不使用任何行,也需要引用现有表。例如,

SELECT TOP 1 1 AS Num FROM msysobjects
UNION ALL
SELECT TOP 1 2 AS Num FROM msysobjects
UNION ALL
SELECT TOP 1 3 AS Num FROM msysobjects

然后使用此计数器表/查询,如下所示:

SELECT D.[Cabinet ID], C.Num & " of " & Count(D.[Door ID]) AS [Door Number], 
       DR.*, DS.*, DP.* 
FROM Counter AS C, 
     ((Doors AS D INNER JOIN DoorRails AS DR ON D.CabinetID=DR.CabinetID)
                  INNER JOIN DoorStiles AS DS ON D.CabinetID=DS.CabinetID)
                  INNER JOIN DoorPanels AS DP ON D.CabinetID=DP.CabinetID
WHERE C.Num <= Count(D.[Door ID])
GROUP BY D.[Cabinet ID] 
ORDER BY D.[Cabinet ID], C.Num

这与您的样本略有不同。不同之处在于每个门都会重复使用机柜ID。由于数量也会重复,我改为替换门号(以&#34; 1 of 2&#34;,&#34; 2 of 2&#34;等等)。