我有一张桌子(SoilSheet):
ID | FieldID | SAMP_NUM | LINE_NUM | Year
LINE_NUM列是介于1和25之间的值。我需要查找具有LINE_NUM行的DISTINCT SAMP_NUM和FieldID ROWS并将它们返回到一行。
在SQL Server中,我可以这样做(缩短为仅返回前5个LINE_NUM列,它几乎立即起作用:
SELECT DISTINCT S1.L1, S2.L2, S3.L3, S4.L4, S5.L5,
S.FieldID, S.SAMP_NUM FROM SoilSheet S
LEFT OUTER JOIN
(SELECT SAMP_NUM, FieldID, LINE_NUM AS L1
FROM SoilSheet WHERE YEAR = 2013 AND LINE_NUM = 1) S1
ON S1.SAMP_NUM = S.SAMP_NUM AND S1.FieldID = S.FieldID
LEFT OUTER JOIN
(SELECT SAMP_NUM, FieldID, LINE_NUM AS L2
FROM SoilSheet WHERE YEAR = 2013 AND LINE_NUM = 2) S2
ON S2.SAMP_NUM = S.SAMP_NUM AND S2.FieldID = S.FieldID
LEFT OUTER JOIN
(SELECT SAMP_NUM, FieldID, LINE_NUM AS L3
FROM SoilSheet WHERE YEAR = 2013 AND LINE_NUM = 3) S3
ON S3.SAMP_NUM = S.SAMP_NUM AND S3.FieldID = S.FieldID
LEFT OUTER JOIN
(SELECT SAMP_NUM, FieldID, LINE_NUM AS L4
FROM SoilSheet WHERE YEAR = 2013 AND LINE_NUM = 4) S4
ON S4.SAMP_NUM = S.SAMP_NUM AND S4.FieldID = S.FieldID
LEFT OUTER JOIN
(SELECT SAMP_NUM, FieldID, LINE_NUM AS L5
FROM SoilSheet WHERE YEAR = 2013 AND LINE_NUM = 5) S5
ON S5.SAMP_NUM = S.SAMP_NUM AND S5.FieldID = S.FieldID
LEFT OUTER JOIN
(SELECT SAMP_NUM, FieldID, LINE_NUM AS L10
FROM SoilSheet WHERE YEAR = 2013 AND LINE_NUM = 10) S10
ON S10.SAMP_NUM = S.SAMP_NUM AND S10.FieldID = S.FieldID
WHERE Year = 2013 AND
(SELECT ID FROM Fields WHERE ID=S.FieldID) IS NOT NULL
ORDER BY S.SAMP_NUM, S.FieldID
我得到了这个
L1 | L2 | L3 | L4 | L5 | FieldID | SAMP_NUM
1 | NULL | NULL | NULL | NULL | 289508 | 4416
1 | NULL | NULL | NULL | NULL | 291501 | 4417
NULL | NULL | 3 | NULL | NULL | 291339 | 4418
NULL | 2 | NULL | NULL | NULL | 291390 | 4418
1 | NULL | NULL | NULL | NULL | 291535 | 4418
1 | 2 | 3 | NULL | NULL | 287808 | 4470
NULL | NULL | NULL | 4 | 5 | 287811 | 4470
但是,转换为MS Access时,这需要永远。我也试过下面这个在SQL Server中慢得多的东西:
SELECT DISTINCT
(SELECT LINE_NUM FROM SoilSheet WHERE LINE_NUM = 1 AND Year = 2013
AND FieldID = S.FieldID AND SAMP_NUM = S.SAMP_NUM) AS L1,
(SELECT LINE_NUM FROM SoilSheet WHERE LINE_NUM = 2 AND Year = 2013
AND FieldID = S.FieldID AND SAMP_NUM = S.SAMP_NUM) AS L2,
(SELECT LINE_NUM FROM SoilSheet WHERE LINE_NUM = 3 AND Year = 2013
AND FieldID = S.FieldID AND SAMP_NUM = S.SAMP_NUM) AS L3,
(SELECT LINE_NUM FROM SoilSheet WHERE LINE_NUM = 4 AND Year = 2013
AND FieldID = S.FieldID AND SAMP_NUM = S.SAMP_NUM) AS L4,
(SELECT LINE_NUM FROM SoilSheet WHERE LINE_NUM = 5 AND Year = 2013
AND FieldID = S.FieldID AND SAMP_NUM = S.SAMP_NUM) AS L5,
FieldID, SAMP_NUM FROM SoilSheet S
WHERE Year = 2013 AND (SELECT ID FROM Fields WHERE ID = S.FieldID)
IS NOT NULL ORDER BY S.SAMP_NUM, S.FieldID
但也永远在Access中。有没有办法在Access中执行此操作?
答案 0 :(得分:0)
我找到了办法:
TRANSFORM LINE_NUM AS L
SELECT SAMP_NUM, FieldID FROM SoilSheet WHERE Year = 2013
GROUP BY SAMP_NUM, FieldID
PIVOT LINE_NUM