如何组合同一个表中的两行数据?

时间:2017-10-04 06:27:57

标签: sql ms-access ms-access-2010

我有一个名为document的表格如下:

document_table

  • DOCUMENT_ID
  • EMPLOYEE_ID
  • 类型(值可以是“transcript”“testimonial”
  • 状态(值可以“仅准备打印”

示例数据如下。

doc_id   employee_id   type         status
--------------------------------------------------
1        S1234         transcript   ready to print
2        S1234         testimonial  ready to print
3        S2345         transcript   ready to print

我希望结果表如下所示。

Result_table

  • EMPLOYEE_ID
  • 成绩单
  • 个人鉴定

我想编写一个sql查询,将单个文档记录合并为一个,基于employee_id,并基于文档类型为transcript或testimonial

doc_id  transcript     testimonial
--------------------------------
S1234   TRUE           TRUE
S2345   TRUE           FALSE

我正在使用MS Access 2010。 我如何实现这一目标?

2 个答案:

答案 0 :(得分:1)

最简单的方法,虽然只返回TRUE有数据的地方,但FALSE只是空字段:

TRANSFORM First("TRUE") AS S
SELECT document.employee_id
FROM document
GROUP BY document.employee_id
PIVOT document.type In ("testimonial","transcript");

不要认为Access SQL识别CASE结构,因此zarruq的替代版本回答:

SELECT
  employee_id,
  IIf(Max(transcript)="transcript","TRUE","FALSE") AS tran, 
  IIf(Max(testimonial)="testimonial", "TRUE","FALSE") AS test
FROM (SELECT
  employee_id,
  type AS transcript,
  '' AS testimonial
FROM document
WHERE type = 'transcript'

UNION ALL

SELECT
  employee_id,
  '' AS transcript,
  type AS testimonial
FROM document
WHERE type = 'testimonial')
GROUP BY employee_id;

答案 1 :(得分:0)

使用SQL,一种方法是在内部查询中使用transcript在单独的列中分隔testimonialunion数据,然后使用max和{ {1}}在外部查询中如下所示,以获得您想要的结果,如下所示。

case

<强>结果:

SELECT
  employee_id,
  CASE
    WHEN MAX(transcript) = 'transcript' THEN 'TRUE'
    ELSE 'FALSE'
  END AS transcript,
  CASE
    WHEN MAX(testimonial) = 'testimonial' THEN 'TRUE'
    ELSE 'FALSE'
  END AS testimonial
FROM (SELECT
  employee_id,
  type AS transcript,
  '' AS testimonial
FROM t1
WHERE type = 'transcript'

UNION ALL

SELECT
  employee_id,
  '' AS transcript,
  type AS testimonial
FROM t1
WHERE type = 'testimonial') t
GROUP BY employee_id;

您可以查看演示 here