2015-12-02 116 views
-1

對於笛卡爾積,使用SQL Server 2012確實存在問題。使用sql server的笛卡爾積

這裏是我的示例查詢:

SELECT A1.* 
    ,RIGHT('00000' + A1.SampleID,5) AS [RealSampleID] 

FROM 
(
SELECT 
    ARS1.SampleID 
    ,ARS1.SampleNo 
FROM TblSamples AS ARS1 
GROUP BY 
    ARS1.SampleNo 
    ,ARS1.SampleID 
) AS [A1] 
INNER JOIN 
(
SELECT 
    ARS2.SampleID 
    ,ARS2.SampleNo 
FROM TblSamples AS ARS2 
WHERE ISNUMERIC(ARS2.SampleID) = 0 
GROUP BY 
    ARS2.SampleNo 
    ,ARS2.SampleID 
) AS A2 
ON A1.SampleNo=A2.SampleNo 

我查詢的結果

enter image description here

預期結果:

enter image description here

Cartesian product Formula: 非數字SampleID X數字SampleIDSampleNo

實施例:

所有SampleNo 。我們在SampleID列和一個不同的非數字值(R00137)中有兩個數值(277和278)。然後這個非數字值(R00137)的RealSampleID將是00277和00278.就像我們在上面的圖像輸出中看到的一樣。

+0

你能提供兩個表的樣本數據? –

+0

試試'ISNUMERIC(ARS2.SampleID)= 1'和'RIGHT('00000'+ A2.SampleID,5)AS [RealSampleID]' - 你想要表A2保存'正確的'sampleIDs – BeanFrog

+0

'SELECT A1。* ,RIGHT('00000'+ A1.SampleID,5)AS [RealSampleID]' - 所有字段的前綴爲A1,否A2;您的預期結果中的最後一行是不可能的。 –

回答

0

沒有樣本數據,這可能不是你想要的,但是這是笛卡爾乘積:

SELECT A1.* 
    ,RIGHT('00000' + A1.SampleID,5) AS [RealSampleID] 
FROM 
(
SELECT 
    ARS1.SampleID 
    ,ARS1.SampleNo 
FROM TblSamples AS ARS1 
GROUP BY 
    ARS1.SampleNo 
    ,ARS1.SampleID 
) AS [A1], 
(
SELECT 
    ARS2.SampleID 
    ,ARS2.SampleNo 
FROM TblSamples AS ARS2 
WHERE ISNUMERIC(ARS2.SampleID) = 0 
GROUP BY 
    ARS2.SampleNo 
    ,ARS2.SampleID 
) AS A2 
+1

這些天我會推薦[使用ANSI標準'CROSS JOIN'語法](http://stackoverflow.com/questions/3918570/what-is-the-difference-between-using-a-cross-join-and -putting-A-逗號th之間-)。 –