2017-02-16 212 views
0

我這裏有兩個表SQL Server查詢連接兩個表

表1

​​

表2

STUDENT |MED_TYPE|REMAINING_MED|ACTIVE 
--------|--------|-------------|------ 
miko |3b  |1.0   |1 
kite |1b  |6.0   |1 
kite |2b  |9.5   |1 
kite |2b  |1.0   |1 
jun  |1b  |10.0   |1 
arri |1b  |8.5   |1 
arri |2b  |9.5   |1 
arri |3b  |1.0   |1 
imko |1b  |6.5   |1 
miko |2b  |8.0   |1 

與此查詢:

SELECT 
    NAME, 
    SUM(CASE 
      WHEN MED_TYPE = '1b' AND MED_STATUS = 'APPROVED' 
       THEN DAYS 
       ELSE 0 
     END) AS USED_1b, 
    SUM(CASE 
      WHEN MED_TYPE = '2b' AND MED_STATUS = 'APPROVED' 
       THEN DAYS 
       ELSE 0 
     END) AS USED_2b 
FROM 
    table1 
GROUP BY 
    NAME 

我得到如下結果:

STUDENT |USED_1b|USED_2b 
----------|-------|------- 
abe  |3.5 |5.0 
arri  |1.5 |0.5 
kiko  |0.0 |0.0 
chen  |4.0 |0.5 
heli  |0.5 |0.0 
miyo  |6.5 |5.5 
mika  |2.0 |1.0 
jun  |3.0 |3.0 
jake  |2.5 |2.5 
zues  |3.5 |2.5 

,但我希望得到如下:

NAME | USED_1b | USED_2b | REMAINING_1b | REMAINING_2b 

remaining_1bremaining_2b從表2列remaining_med現身,他們可以與MED類型分類。連接兩張表的是姓名和學生。此外,我想檢查學生是否活動。如果不活躍,它將不會顯示在結果表中。

這將是什麼正確的查詢?我不知道如何使用連接或聯合。我是SQL Server的新手。

順便說一句,表1和表2和結果只是整個表的一部分。如果我在這裏發佈所有內容將會太長。

+1

附加預期的輸出也在這裏 –

+0

什麼是remaining_1b和remaining_2b預期的要求? – FreedomPride

回答

1

你可以分別找到和然後加入。

像這樣:

select t1.name, 
    t1.USED_1b, 
    t1.USED_2b, 
    t2.remaining_1b, 
    t2.remaining_2b 
from (
    select name, 
     SUM(case when MED_TYPE = '1b' 
        and MED_STATUS = 'APPROVED' then DAYS else 0 end) as USED_1b, 
     SUM(case when MED_TYPE = '2b' 
        and MED_STATUS = 'APPROVED' then DAYS else 0 end) as USED_2b 
    from table1 
    group by name 
    ) t1 
join (
    select student, 
     SUM(case when MED_TYPE = '1b' then remaining_med else 0 end) as remaining_1b, 
     SUM(case when MED_TYPE = '2b' then remaining_med else 0 end) as remaining_2b 
    from table2 
    group by student 
    ) t2 on t1.name = t2.student; 
+0

哇..感謝男人..似乎是我確切需要的:) btw ..什麼是這個查詢的linq等價物?因爲我會在mvc中使用它 – silver01