我正在北风数据库上进行培训但遇到了一个案例陈述,我在下面提出查询并希望得到帮助。
问题是我希望Shippeddate列中的记录包含一些文本,在这种情况下,我放置了' ddd'当它上面有NULL时,NULL会一直出现在结果集中。
SELECT OrderID,
CONVERT(VARCHAR(10), OrderDate, 103) AS OrderDate,
CONVERT(VARCHAR(10), RequiredDate, 103) AS RequiredDate,
CASE ShippedDate
WHEN NULL THEN 'ddd'
ELSE CONVERT(VARCHAR(10), ShippedDate, 103)
END AS ShippedDate
-- Why is this not working
,
[UnitPrice] AS UnitPriceOnOrder,
[Quantity] AS QuantityOnOrder,
[Discount] AS DiscountOnOrder,
CompanyName_II AS CustomerCompanyName,
ContactName_II AS CustomerContact,
ContactTitle_II AS CustomerContactTitle,
City_II AS CustomerCity,
Country_II AS CustomerCountry,
ProductName,
CategoryName,
[Description] AS CategoryDescription,
UnitsInStock,
UnitsOnOrder,
UnitsInStock - UnitsOnOrder AS AvailableUnitsInStock,
FirstName + ' ' + LastName AS EmployeeName
FROM ##NorthwindTestI
WHERE [Quantity] > 10
AND ShippedDate > '19970101'
OR [UnitPrice] > 10
OR Country_II = 'USA'
OR FirstName + ' ' + LastName = 'Janet Leverling'
ORDER BY
--[Quantity]
ShippedDate
答案 0 :(得分:1)
尝试使用ISNULL()
代替:
所以而不是
CASE ShippedDate
WHEN NULL THEN 'ddd'
ELSE CONVERT(VARCHAR(10), ShippedDate, 103)
END AS ShippedDate
使用:
ISNULL(CONVERT(VARCHAR(10),ShippedDate,103),'ddd')
因此您的查询将如下:
SELECT OrderID,
CONVERT(VARCHAR(10), OrderDate, 103) AS OrderDate,
CONVERT(VARCHAR(10), RequiredDate, 103) AS RequiredDate,
ISNULL(CONVERT(VARCHAR(10),ShippedDate,103),'ddd') AS ShippedDate
-- Why is this not working
,
[UnitPrice] AS UnitPriceOnOrder,
[Quantity] AS QuantityOnOrder,
[Discount] AS DiscountOnOrder,
CompanyName_II AS CustomerCompanyName,
ContactName_II AS CustomerContact,
ContactTitle_II AS CustomerContactTitle,
City_II AS CustomerCity,
Country_II AS CustomerCountry,
ProductName,
CategoryName,
[Description] AS CategoryDescription,
UnitsInStock,
UnitsOnOrder,
UnitsInStock - UnitsOnOrder AS AvailableUnitsInStock,
FirstName + ' ' + LastName AS EmployeeName
FROM ##NorthwindTestI
WHERE [Quantity] > 10
AND ShippedDate > '19970101'
OR [UnitPrice] > 10
OR Country_II = 'USA'
OR FirstName + ' ' + LastName = 'Janet Leverling'
ORDER BY
--[Quantity]
ShippedDate
答案 1 :(得分:0)
使用WHEN ShippedDate IS NULL
代替CASE ShippedDate WHEN NULL
:
SELECT .....,
CASE WHEN ShippedDate IS NULL
THEN 'ddd'
ELSE CONVERT(VARCHAR(10), ShippedDate, 103)
END AS ShippedDate
.....