2011-08-20 79 views
0

我開始了與一個粗略的草稿查詢:我很好奇,爲什麼這些結果是不同的

SELECT S.Type, 
COUNT(DISTINCT C.StateProvince) 
FROM INV_LINE_ITEM ILI JOIN STOVE S ON ILI.FK_StoveNbr = S.SerialNumber 
JOIN INVOICE I ON I.InvoiceNbr = ILI.FK_InvoiceNbr 
JOIN CUSTOMER C ON I.FK_CustomerID = C.CustomerID 
WHERE C.Country = 'USA' 
AND S.Type IN (SELECT S.Type 
FROM INV_LINE_ITEM ILI JOIN STOVE S ON ILI.FK_StoveNbr = S.SerialNumber 
JOIN INVOICE I ON I.InvoiceNbr = ILI.FK_InvoiceNbr 
JOIN CUSTOMER C ON I.FK_CustomerID = C.CustomerID 
WHERE C.Country = 'CAN') 
GROUP BY S.Type; 

它返回的結果如下:

Type    
--------------- ----------- 
FiredAlways  9 
FiredNow  8 

所以,一旦我得到了查詢以我想要的方式工作,我決定對它進行一些格式化,並且我注意到一些奇怪的東西。

這個查詢會產生上述結果:

SELECT 
CAST(S.Type as CHAR (10)) AS 'Stove Type', 
COUNT(DISTINCT C.StateProvince) AS 'Number of Sales' 
FROM STOVE S, INV_LINE_ITEM ILI, INVOICE I, CUSTOMER C 
WHERE S.SerialNumber = ILI.FK_StoveNbr 
AND ILI.FK_InvoiceNbr = I.InvoiceNbr 
AND I.FK_CustomerID = C.CustomerID 
AND C.Country = 'USA' 
AND S.Type IN 
(SELECT S.Type 
FROM STOVE S, INV_LINE_ITEM ILI, INVOICE I, CUSTOMER C 
WHERE S.SerialNumber = ILI.FK_StoveNbr 
AND ILI.FK_InvoiceNbr = I.InvoiceNbr 
AND I.FK_CustomerID = C.CustomerID 
AND C.Country = 'CAN') 
GROUP BY S.Type; 

但此查詢不:

SELECT 
CAST(S.Type as CHAR (10)) AS 'Stove Type', 
COUNT(DISTINCT C.StateProvince) AS 'Number of Sales' 
FROM STOVE S, INV_LINE_ITEM ILI, INVOICE I, CUSTOMER C 
WHERE S.SerialNumber = ILI.FK_StoveNbr 
AND ILI.FK_InvoiceNbr = I.InvoiceNbr 
AND I.FK_CustomerID = C.CustomerID 
AND C.Country = 'USA' 
AND S.Type IN 
(SELECT CAST(S.Type as CHAR (10)) 
FROM STOVE S, INV_LINE_ITEM ILI, INVOICE I, CUSTOMER C 
WHERE S.SerialNumber = ILI.FK_StoveNbr 
AND ILI.FK_InvoiceNbr = I.InvoiceNbr 
AND I.FK_CustomerID = C.CustomerID 
AND C.Country = 'CAN') 
GROUP BY S.Type; 

相反,它會產生這樣的:

Stove Type Number of Sales 
---------- --------------- 
FiredNow 8 

而且我不真的確定爲什麼。我原以爲我只編輯第10行的S.Type以匹配第2行的S.Type,但很明顯發生了更多事情。

回答

3

因爲「FiredAlways」超過了要投射的10個角色。

+0

你是對的。我將CAST改爲11,一切正常。感謝您的幫助。 – krebshack

相關問題