简体   繁体   中英

How to "roll-up"/aggregate rows from a badly designed table with SQL?

So I'm working with this badly designed table, but it's from another department and I need the data so I have no control over it. How can I get in a proper state? I'm working with MS Access so unfortunately I don't have access to "advanced" SQL functions like partition by, or row_number, etc.

This is the bad table:

KeyID PA QL RuleName
1111 X YYY
1111 X ZZZ
1111 X OOO

I want my final table to look like this:

KeyID PA QL RuleNamePA RuleNameQL RuleNameQL2
1111 X X YYY ZZZ OOO

Any help would be appreciated!

Assuming PA and QL fields are Yes/No type and there is a unique identifier field (such as autonumber type), consider:

Query1: normalize table structure

SELECT ID, KeyID, IIf(PA, "PA", "QL") AS Cat, RuleName FROM Table2;
ID KeyID Cat RuleName
1 1111 PA yyy
2 1111 QL zzz
3 1111 QL ooo

Query2: pivot data with CROSSTAB

TRANSFORM First(RuleName) AS FirstOfRuleName
SELECT KeyID
FROM Query1
GROUP BY KeyID
PIVOT "RuleName" & [Cat] & DCount("*","Query1","Cat='" & [Cat] & "' AND ID<" & [ID])+1;

If there is no unique identifier ID field, change the DCount to:
DCount("*","Query1","Cat='" & [Cat] & "' AND KeyID & Cat & RuleName<'" & [KeyID] & [Cat] & [RuleName] & "'")+1

Actually, can eliminate Query1 if you do the Cat calculation (3 times) in the PIVOT clause then just reference table instead of query in the CROSSTAB.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM