我有一个名为document的表格如下:
document_table
示例数据如下。
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 :
我想编写一个sql查询,将单个文档记录合并为一个,基于employee_id,并基于文档类型为transcript或testimonial
doc_id transcript testimonial
--------------------------------
S1234 TRUE TRUE
S2345 TRUE FALSE
我正在使用MS Access 2010。 我如何实现这一目标?
答案 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
在单独的列中分隔testimonial
和union
数据,然后使用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