我正在使用Excel VBA进行SQL查询。 下面是我正在使用的SQL字符串:
SELECT DESC, SEQNUM, INSTRUCTION FROM TABLE
WHERE DESC = 'ITEM1' AND SEQNUM <=3
以下是查询结果:
DESC SEQNUM INSTRUCTION
ITEM1 1 002.000
ITEM1 2 137.000
ITEM1 3 005.000
如何使查询结果如下所示?
DESC SEQNUM1 SEQNUM2 SEQNUM3
ITEM1 002.000 137.000 005.000
答案 0 :(得分:0)
像这样,只要有一个DESC-SEQNUM :
SELECT DESC, S1.INSTRUCTION, S2.INSTRUCTION, S3.INSTRUCTION
FROM TABLE AS S1 INNER JOIN
TABLE AS S2 ON S1.DESC = S2.DESC
INNER JOIN TABLE AS S3 ON S3.DESC=S1.DESC
对于Access SQL,您可能需要包含如下所述的INNER JOIN: SQL multiple join statement Access SQL的结果是:
SELECT DESC, S1.INSTRUCTION, S2.INSTRUCTION, S3.INSTRUCTION
FROM (TABLE AS S1 INNER JOIN
TABLE AS S2 ON S1.DESC = S2.DESC)
INNER JOIN TABLE AS S3 ON S3.DESC=S1.DESC
正如评论中所提到的,这假设没有遗漏给DESC的分配。 如果有,你需要将INNER JOIN更改为LEFT JOINs :
SELECT DESC, S1.INSTRUCTION, S2.INSTRUCTION, S3.INSTRUCTION
FROM (TABLE AS S1 LEFT JOIN
TABLE AS S2 ON S1.DESC = S2.DESC)
LEFT JOIN TABLE AS S3 ON S3.DESC=S1.DESC
答案 1 :(得分:0)
如果支持 - 在这里执行自我完全外连接,ANSI SQL语法:
select coalesce(t1.desc, t2.desc, t3.desc),
t1.INSTRUCTION SEQNUM1,
t2.INSTRUCTION SEQNUM2,
t3.INSTRUCTION SEQNUM3
from (select * from TABLE where SEQNUM = 1) t1
full outer join (select * from TABLE where SEQNUM = 2) t2 on t1.desc = t2.desc
full outer join (select * from TABLE where SEQNUM = 3) t3 on t2.desc = t3.desc
答案 2 :(得分:0)
Sql = " TRANSFORM INSTRUCTION " & vbCr & _
" SELECT DISTINCT DESC " & vbCr & _
" FROM [Sheet$] " & vbCr & _
" GROUP BY DESC" & vbCr & _
" order by DESC asc " & vbCr & _
" PIVOT SEQNUM "
// [Sheet$] = your TABLE