没有第一个表ID的表联接?

时间:2018-07-17 16:10:48

标签: sql join

我在以下查询中提出的问题是,正确连接到dm_fiscal_cal表的工作方式是什么? 我了解您可以加入没有pk fk关系的字段,但是当它与job_order表无关时(在mom.approval_wes = fc.week_ending_sunday上)如何工作?

SELECT 
    jo.order_id
    ,cd.client_id
    ,st.staff_name
    ,c.company_name
    ,ma.market_code
    ,SUM(mom.gross_profit)
FROM 
---- main table for order information
-- anchoring the query in this table means only clients with orders will return
    job_order as jo
LEFT JOIN 
--- main mart table for "aqent staff" coordinator id is the agent
    dm_staffhier_d as st
        on jo.coordinator_id = st.person_id   
---- secondary table for clients and their markets each order is related to a "client / market" combination. 
--- You must join on both to identify the correct market for the client where the order exists
LEFT JOIN
    client_default as cd    
        on jo.client_id = cd.client_id and 
        jo.market_id=cd.market_id  
--- primary table for clients
--- each client id is represented once and only once in this tbl
LEFT JOIN 
client as c
    on cd.client_id=c.client_id

--- market lookup table. there are market_ids that relate to many objects (orders, clients, people, leads, ..etc)
--- always make sure you're anchoring the market_id (Fk) on the correct object for the query results. You can (and often do) need
--  to alias this table for multiple uses
LEFT JOIN
    market as ma
        on jo.market_id= ma.market_id   

---- main finanacial data mart tbl. each order fee for each week, for each client is represented.
--- you can join on order id for this query. You could use otherer relations ships for other queries
LEFT JOIN
    dm_mainordermetrics_f as mom
        on jo.order_id=mom.order_id

--- fiscal calendar tbl
--- we're joining this to the financial tbl because we're looking for GP$ in a certain period. That period is 
--- easily found by using the dm_fiscal_cal tbl (fiscal year 2017).
RIGHT JOIN
    dm_fiscal_cal as fc
        on mom.approval_wes = fc.week_ending_sunday
WHERE 
--- market requirement for LA, and BOS
    ma.short_description IN ('Los Angeles', 'Boston')
--- not a good solution for this - check having clause 
--    AND mom.gross_profit >0
    AND  fc.fiscal_year = 2017
GROUP BY 
     jo.order_id
    ,st.staff_name
    ,cd.client_id
    ,c.company_name
    ,ma.market_code

having sum(mom.gross_profit) > 0

order by 4,1
--- you should get 1509 rows

1 个答案:

答案 0 :(得分:0)

所以,看来您是StackOverflow和SQL的新手。首先,我将尝试回答您的原始问题。

我的解释是,您要问第二个LEFT JOIN(有时也称为LEFT OUTER JOIN)在SQL中是否是有效的语句,即使它不包含{{1 }}或job.order_id

该问题的答案是,该语句是有效的,它将运行。这并不意味着它将必然返回任何记录,或者它正在完全按照您希望的方式进行操作。

很抱歉,这不是您想要的问题,但这使我想起第二点。

您应该编辑原始问题,以更清楚地了解您想知道的内容。如果您在询问之前自行进行了研究,请提供指向您正在浏览的站点的链接。在查询的fiscal.cal_id子句中的表上添加相关列。最后,请仔细考虑您不了解的具体含义。也许突出显示您的问题中的那几行代码。

所有这些都将帮助我们更好地回答您的问题。