SQL Server 中级
Ginger Grant
Instructor
无数据时,空字段为 NULL
NULL 不是数字,无法用 =, <, > 查找或比较
判断一列是否为 NULL,使用 IS NULL 和 IS NOT NULL
SELECT Country, InternetUse, Year
FROM EconomicIndicators
WHERE InternetUse IS NOT NULL
+-------------------+-------------------+------------+
|Country |InternetUse |Year |
|-------------------+-------------------+------------+
|Afghanistan |4.58066992 |2011 |
|Albania |49 |2011 |
|Algeria |14 |2011 |
....
+-------------------+-------------------+------------+
SELECT Country, InternetUse, Year
FROM EconomicIndicators
WHERE InternetUse IS NULL
+-------------------+-------------------+------------+
|Country |InternetUse |Year |
|-------------------+-------------------+------------+
|Angola |NULL |2013 |
|Argentina |NULL |2013 |
|Armenia |NULL |2013 |
....
+-------------------+-------------------+------------+
'' 查找空白SELECT Country, GDP, Year
FROM EconomicIndicators
WHERE LEN(GDP) > 0
+-------------------+-------------------+------------+
|Country |GDP |Year |
|-------------------+-------------------+------------+
|Afghanistan |54852215624 |2011 |
|Albania |29334492905 |2011 |
|Algeria |453558093404 |2011 |
....
+-------------------+-------------------+------------+
SELECT GDP, Country,
ISNULL(Country, 'Unknown') AS NewCountry
FROM EconomicIndicators
+-------------------+----------------+----------------+
|GDP |Country |NewCountry |
|-------------------+----------------+----------------+
|5867920022 |NULL |Unknown |
|597873038497 |South Africa |South Africa |
|1474091271101 |NULL |Unknown |
...
+-------------------+----------------+----------------+
/*Substituting values from one column for another with ISNULL*/
SELECT TradeGDPPercent, ImportGoodPercent,
ISNULL(TradeGDPPercent, ImportGoodPercent) AS NewPercent
FROM EconomicIndicators
+-------------------+------------------+----------------+
|TradeGDPPercent |ImportGoodPercent |NewPercent |
|-------------------+------------------+----------------+
|NULL |56.7 |56.7 |
|52.18720739 |51.75273421 |52.18720739 |
|NULL |NULL |NULL |
...
+-------------------+------------------+----------------+
COALESCE 返回第一个非缺失值
COALESCE( value_1, value_2, value_3, ... value_n )
value_1 为 NULL 且 value_2 非 NULL,返回 value_2value_1、value_2 为 NULL 且 value_3 非 NULL,返回 value_3SELECT TradeGDPPercent, ImportGoodPercent,
COALESCE(TradeGDPPercent, ImportGoodPercent, 'N/A') AS NewPercent
FROM EconomicIndicators
+-------------------+--------------------+---------------+
|TradeGDPPercent |ImportGoodPercent |NewPercent |
|-------------------+--------------------+---------------+
|NULL |56.7 |56.7 |
|NULL |NULL |N/A |
|52.18720739 |51.75273421 |52.18720739 |
+-------------------+--------------------+---------------+
SQL Server 中级