SQL Server查询连接两个表

时间:2017-02-16 03:47:55

标签: sql sql-server join union

我这里有两张桌子

表1

NAME      |MED_TYPE |MED_STATUS  |DAYS
----------|---------|------------|--------
miyo      |1b       |APPROVED    |0.5
miya      |1b       |APPROVED    |1.0
jun       |3b       |APPROVED    |1.0
kite      |3b       |APPROVED    |1.0
hans      |1b       |APPROVED    |1.0
mark      |1b       |APPROVED    |2.0
jep       |1b       |APPROVED    |1.0
Gali      |2b       |APPROVED    |0.5
Hera      |1b       |APPROVED    |0.5
Zues      |2b       |APPROVED    |0.5

表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类型进行分类。连接这两个表的是名称和学生。另外我想检查学生是否活跃。如果未激活,它将不会显示在结果表中。

对此有什么正确的查询?我不知道如何使用join或union。我是SQL Server的新手。

BTW,表1和表2以及结果只是整个表的一部分。如果我在这里张贴所有内容将会太久。

1 个答案:

答案 0 :(得分: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;