在查询中使用多列来下拉列表

时间:2016-08-24 14:22:16

标签: sql sql-server ms-access

我有一个包含3个材质子表单的表单,每个子表单都有一个“名称”列。我想要做的是在查询中捕获这些名称,以制作Usage子表单的下拉列表,而不是依赖于用户输入与相关材料子表中显示的完全相同的名称。

我能得到的最接近的是以下SQL

ggplot

这会得到如下结果:

SELECT    mo.OrderID, mos.SheetName, moe.ExtrusionName, mom.MiscName
FROM        dbo.tblMatOrder AS mo INNER JOIN
                     dbo.tblMatOrderExtrusion AS moe ON mo.OrderID = moe.OrderID INNER JOIN
                     dbo.tblMatOrderMisc AS mom ON mo.OrderID = mom.OrderID INNER JOIN
                     dbo.tblMatOrderSheet AS mos ON mo.OrderID = mos.OrderID

我想得的是以下内容:

| ORDERID | SHEETNAME | EXTRUSIONNAME | MISCNAME |
| 123     | SHEET1    | EXT1          | MISC1    |
| 123     | SHEET2    | EXT1          | MISC1    |

但是对于我的生活,我无法弄清楚WHERE子句或如何获得聚合函数将3“名称”列组合成单个列,如果可能的话。

4 个答案:

答案 0 :(得分:3)

你可以做这样的事情

SELECT DISTINCT mo.OrderID, mos.SheetName AS 'MaterialName'
FROM dbo.tblMatOrder AS mo
INNER JOIN dbo.tblMatOrderSheet AS mos ON mo.OrderID = mos.OrderID
WHERE mo.OrderID = @orderId    
UNION
SELECT DISTINCT mo.OrderID, mom.MiscName AS 'MaterialName'
FROM dbo.tblMatOrder AS mo
INNER JOIN dbo.tblMatOrderMisc AS mom ON mo.OrderID = mom.OrderID
WHERE mo.OrderID = @orderId      
UNION
SELECT DISTINCT mo.OrderID, moe.ExtrusionName AS 'MaterialName'
FROM dbo.tblMatOrder AS mo
INNER JOIN dbo.tblMatOrderExtrusion AS moe ON mo.OrderID = moe.OrderID 
WHERE mo.OrderID = @orderId  

答案 1 :(得分:1)

如果所有表中都存在orderID,那么它应该很简单,如下所示

SELECT  OrderID,SheetName as 'MaterialName' FROM dbo.tblMatOrderSheet 
UNION ALL
SELECT OrderID,ExtrusionName as 'MaterialName' FROM  dbo.tblMatOrderExtrusion
UNION ALL
SELECT OrderID,MiscName as 'MaterialName' FROM dbo.tblMatOrderExtrusion

答案 2 :(得分:0)

SELECT Distinct  OrderID,SheetName as 'MaterialName' FROM dbo.tblMatOrderSheet 
UNION 
SELECT Distinct   OrderID,ExtrusionName as 'MaterialName' FROM  dbo.tblMatOrderExtrusion
UNION 
SELECT Distinct  OrderID,MiscName as 'MaterialName' FROM dbo.tblMatOrderExtrusion

答案 3 :(得分:0)

好吧,我设法用更多的谷歌搜索来浏览一个不同的解决方案。我无法让UNION工作。正如所写,我得到一个错误,标量@OrderID需要声明。删除该行后,我收到一个错误,即多部分标识符" mom.MiscName"无法受约束。

最终为我工作的是将原始查询保存为自己的视图,然后对该查询运行CROSS APPLY。

SELECT   DISTINCT   OrderID, MatName
FROM            dbo.vueMatOrderMatNames
CROSS APPLY
(
     VALUES  ('SheetName', SheetName), ('ExtrusionName', ExtrusionName), ('MiscName', MiscName)
) c(col, MatName)