SQL WHERE子句多次相同列?

时间:2017-02-20 22:58:52

标签: sql database

我的表格如下所示,我们称之为Table1:

ID  | value  |  formID
----------------------
25   Business  1001
16   John      1001
5    2/20/17   1001
30   FormXYZ   1001
25   Nursing   2345
16   Sam       2345
5    1/15/17   2345
30   FormXYZ   2345
25   Tech      4500
16   Sam       4500
5    2/1/17    4500
30   FormC     4500

ID 是该字段的唯一标识符:
25 =部门
16 =姓名
5 =日期

30 =表单名称,我们有多个不同的表单,我只需要FormXYZ数据。


FormID 是提交的每个表单的唯一ID,表单包含3个字段。

我一直在尝试编写一个查询,如果可能的话,检索所有类似的数据:

Department  | Name  | Date
Business      John    2/20/17
Nursing       Sam     1/15/17

以下是我一直在尝试的,嵌套和CASE似乎对我不适合,所以我在这里发帖,我回到了我开始的地方。

SELECT value
FROM Table1
WHERE ID = '25'
  UNION ALL
SELECT value
FROM Table1
WHERE ID = '16'
  UNION ALL
SELECT value
FROM Table1
WHERE ID = '5'
  UNION ALL
SELECT value
FROM Table1
WHERE ID = '30' and value = 'FormXYZ'

2 个答案:

答案 0 :(得分:1)

在SQL中转置数据的一种方法是使用case语句并使用group汇总数据:

select 
    formID,
    max(case when ID=25 then value else null end) as Department,
    max(case when ID=16 then value else null end) as Name,
    max(case when ID=5 then value else null end) as Date
from Table1
group by formID

这会产生:

formid Department Name Date 
1001   Business   John 2/20/17 
2345   Nursing    Sam  1/15/17 
4500   Tech       Sam  2/1/17 

您可以根据需要添加where子句。这应该在一次扫描中获得数据。

答案 1 :(得分:0)

select dp.value as department,
       n.value as name,
       dt.value as date
from
    (select formID, value from table1 where id = 25) as dp
    inner join (select formID, value from table1 where id = 16) as n
               on dp.formID = n.formID
    inner join (select formID, value from table1 where id = 5) as dt
               on dp.formID = dt.formID
    inner join (select formID, value from table1 where id = 30) as f
               on dp.formID = f.formID
where f.value = 'FormXYZ';

OR

select
    case when id = 25 then value end as department,
    case when id = 5 then value end as date,
    case when id = 16 then value end as name
from table1
where formId in (select formID from table1
                 where id = 30 and value = 'FormXYZ')
      and id in (5,16,25);