如何使用文本多级映射数据?

时间:2014-03-10 16:34:19

标签: sql ms-access

如何编写sql语句?

Table_Product
+------------------+
|     Product      |
+------------------+
|      AAA         |
|      ABB         |
|      ABC         |
|      ACC         |
+------------------+


Table_Mapping

+---------------+---------------+
|  ProductGroup |  ProductName  |
+---------------+---------------+
|     A*        |    Product1   |
|     ABC       |    Product2   |
+---------------+---------------+

我需要以下结果:

+------------+---------------+
|  Product   |  ProductName  |
+------------+---------------+
|    AAA     |   Product1    |
|    ABB     |   Product1    |
|    ABC     |   Product2    |
|    ACC     |   Product1    |
+------------+---------------+

谢谢, TOM

3 个答案:

答案 0 :(得分:1)

以下查询执行从Access应用程序本身运行时所描述的内容:

    SELECT Table_Product.Product, Table_Mapping.ProductName
    FROM
        Table_Product
        INNER JOIN
        Table_Mapping
            ON Table_Product.Product = Table_Mapping.ProductGroup
    WHERE InStr(Table_Mapping.ProductGroup, "*") = 0
UNION ALL
    SELECT Table_Product.Product, Table_Mapping.ProductName
    FROM
        Table_Product
        INNER JOIN
        Table_Mapping
            ON Table_Product.Product LIKE Table_Mapping.ProductGroup
    WHERE InStr(Table_Mapping.ProductGroup, "*") > 0
        AND Table_Product.Product NOT IN (SELECT ProductGroup FROM Table_Mapping)
ORDER BY 1

答案 1 :(得分:0)

你会想要使用CASE WHEN。试试这个:

Select Product, (CASE
  WHEN Product = 'AAA' THEN 'Product1'
  WHEN Product = 'ABB' THEN 'Product1'
  WHEN Product = 'ABC' THEN 'Product2'
  WHEN Product = 'ACC' THEN 'Product1'
  ELSE Null END) as 'ProductName'
from Table_Product
order by Product

答案 2 :(得分:0)

如果这实际上是如何实现的,那么你可以

Select Product, ProductName
From Table_Product P
inner join Table_Mapping M
On M.Product_Group & '*' like  P.Product

您必须删除将A* Product记录更改为A Product。即你不能在记录中嵌入通配符。如果你想在开始时使用通配符,它​​将会运行得慢很多。