Iterate on 1 table to get data from other tableand get combined result from both table

时间:2016-02-12 19:30:38

标签: sql-server loops

I have 3 tables. The first table 'Status_Mapping' has following columns

Status_orignal  Status_Site
accepted        Call Verified
duplicate       Duplicate Leads
dq              DQ

Now the other table 'Lead_transaction' has the columns

Lead_transaction_id   Rate   Status
  11               0.01   accepted
  12               0.02   accepted
  13               0.01   dublicate

and then there is a 'Lead_Instance' table with

Lead_Instance_id   Lead_transaction_id   product_id  affiliate_id
 1                    11                   6            10
 2                    12                   7            11
 3                    13                   6            10

What I want to do is loop through the status_mapping table and get the count(lead_isntance_id) and sum(rate) for each status and then site status from the previous table with product_id = 6 and affiliate_id = 10 My End result should be like

Total              Sum   Status
 1                 0.01   Call Verified
 1                 0.01   Duplicate Leads
 0                 0.00    dq

Any help would be appreciated

1 个答案:

答案 0 :(得分:2)

First, understand that you're not "looping", rather you're joining similar datasets:

SELECT  S.Status_Site AS [Status], 
        ISNULL(SUM(CASE WHEN L.Status IS NOT NULL THEN 1 END), 0) AS [Total Occurrences], 
        ISNULL(SUM(L.Rate), 0) AS [Rate Sum]
FROM Status_Mapping S
LEFT OUTER JOIN Lead_Instance L
    ON S.Status_Original = L.Status
GROUP BY S.Status_Site

EDIT:

If you want to use coalesce:

SELECT  S.Status_Site AS [Status], 
        COALESCE(SUM(CASE WHEN L.Status IS NOT NULL THEN 1 END), 0) AS [Total Occurrences], 
        COALESCE(SUM(L.Rate), 0) AS [Rate Sum]
FROM Status_Mapping S
LEFT OUTER JOIN Lead_Instance L
    ON S.Status_Original = L.Status
GROUP BY S.Status_Site

Since you said you've never heard of COALESCE before (all it does is take the first non-null value in the list):

https://msdn.microsoft.com/en-us/library/ms190349.aspx