借助SQL查询来分解物料清单

时间:2018-07-01 06:43:12

标签: sql sql-server

我正在尝试将BOM细分为最低的项目。我有2张桌子。

表A:

class DataService {
    static let shared = DataService()
    private init() {}

    public fileprivate(set) var baseDB = Database.database().reference()
    public fileprivate(set) var userDB = Database.database().reference()
    public fileprivate(set) var userPostDB = Database.database().reference()

    var currentUser: DatabaseReference {
        let userID = UserDefaults.standard.value(forKey: "uid") as! String

        return Database.database()
            .reference()
            .child(byAppendingPath: "user")
            .child(byAppendingPath: userID)
    }


    func createNewAccount(uid: String, user: Dictionary<String, String>) {
        // A User is born?

        userDB.child(byAppendingPath: uid).setValue(user)
    }

    func createNewUserPost(userpost: Dictionary<String, AnyObject>) {
        // Save the Post
        // userPostDB is the parent of the new USERPOST: "userposts".
        // childByAutoId() saves the userpost and gives it its own ID.

        let firebaseNewUserPost = userPostDB.childByAutoId()

        // setValue() saves to Firebase.

        firebaseNewUserPost?.setValue(userpost)
    }
}

表B

ITEM        FORMULA
--------------------
7024        BDD39           
7024        BDD94         

关于如何用表B中的所有3个项目替换表A中的项目有任何提示吗?

我的预期输出是:

FORMULA         RAW_ITEMS
---------------------------------------
BDD94           BioxDD 94 RMW0005                                
BDD94           BioxDD 94 RMP0007                  
BDD94           BioxDD 94 RMD0010                                   
BDD94           BioxDD 94 RMH0009                    
BDD39           BioxDD 39 RMA0005                              
BDD39           BioxDD 39 RMW0006                               
BDD39           BioxDD 39 RMS0005   

感谢您的帮助。

3 个答案:

答案 0 :(得分:2)

通过使用CONCAT函数和INNER JOIN,您可以获得所需的输出:

SELECT CONCAT(a.Item, ' ', a.Formula) AS Item,
       b.raw_items
 FROM TableA a INNER JOIN TableB b
   ON ( b.Formula = a.Formula )
WHERE a.Formula = 'BDD39';

或在未将值 BDD39 分配给 Formula 的情况下使用:

SELECT Item, raw_items
  FROM
(  
SELECT CONCAT(a.Item, ' ', a.Formula) AS Item,
       b.raw_items,
       dense_rank() over (order by a.Formula) dr
 FROM TableA a INNER JOIN TableB b
   ON ( b.Formula = a.Formula )
) q
WHERE q.dr = 1;

SQL Fiddle Demo

答案 1 :(得分:0)

您要的只是一个内部联接,这是SQL的基础:

SELECT 
A.ITEM,
A.FORMULA,
B.RAW_ITEMS
FROM 
TableA A
INNER JOIN
TableB B
ON A.Formula = B.Formula

如果所有内容都必须放在一列中,则只需将其连接起来。这是一种方法

SELECT 
A.ITEM + ' ' +
A.FORMULA + ' ' + 
B.RAW_ITEMS As Item
FROM 
TableA A
INNER JOIN
TableB B
ON A.Formula = B.Formula

这是另一个

SELECT CONCAT(
A.ITEM, ' ',
A.FORMULA,' ',
B.RAW_ITEMS) As Item
FROM 
TableA A
INNER JOIN
TableB B
ON A.Formula = B.Formula

答案 2 :(得分:0)

SELECT CONCAT(ITEM, " ", TA.FORMULA, " ",  RAW_ITEMS) AS ITEM
FROM TABLEA TA, TABLEB TB
WHERE TA.FORMULA = TB.FORMULA