我很好奇为什么这些结果不同

时间:2011-08-20 23:53:10

标签: sql sql-server sql-server-2008

我开始时的粗略草稿查询:

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,但很明显发生了更多。

1 个答案:

答案 0 :(得分:3)

因为“FiredAlways”超过了你要投射的10个字符。