在'NULL'上填充NULL周末

时间:2013-10-08 12:05:11

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

我使用这些数据创建了数据库:

市场表:

ID| Name    | Location
1 | NYSE    | USA
2 | NASDAQ  | USA
3 | CME     | USA
4 | Euronext| Netherlands

周末表:

ID| DayOff
1 | 2013-11-28
2 | 2013-12-25
3 | 2014-01-01
4 | 2014-01-21
5 | 2014-02-18
6 | 2014-03-29
7 | 2014-05-27
8 | 2014-07-04
9 | 2014-09-02
10| NULL

m2m_market_weekends表:

market_id | weekend_id
1         | 1
1         | ... 
1         | 9
2         | 1
2         | ...
2         | 9
2         | 1
3         | ...
3         | 9
5         | 10

编写查询,使用等号ID对数据进行分组,并将所有日期附加到一个字符串:

SELECT [Market].Name as [MarketName],
   IsNull(STUFF((SELECT '; ' + CAST([DayOff] AS nvarchar(15)) FROM [Weekend] FOR    XML PATH ('')),1, 1, ''), 'NULL') as [DayOff]
FROM [m2m_market_weekends]
INNER JOIN [Market]  ON [m2m_market_weekends].[market_id]  =  [Market].[ID]
INNER JOIN [Weekend] ON [m2m_market_weekends].[weekend_id] = [Weekend].[ID]
GROUP BY [Market].Name

得到:

MarketName | DayOff
NYSE       | 2013-11-28; ...
NASDAQ     | 2013-11-28; ...
CME        | 2013-11-28; ...
Euronext   | 2013-11-28; ...  <-- This market have NULL value at Weekend table

如何修复此问题,此查询返回Euronext DayOff ='NULL'?

1 个答案:

答案 0 :(得分:1)

您的相关子查询与主查询之间没有链接(即您将为所有市场带回所有周末的列表)。这应该适合你:

SELECT  MarketName = Market.Name,
        DayOff = ISNULL(STUFF(( SELECT  '; ' + CAST(DayOff AS VARCHAR(15)) 
                                FROM    m2m_market_weekends m2m
                                        INNER JOIN Weekend w
                                            ON m2m.weekend_id = w.ID
                                WHERE   m2m.market_id =  Market.ID
                                ORDER BY DayOff
                                FOR XML PATH (''), TYPE
                                ).value('.', 'NVARCHAR(MAX)'),
                        1, 1, ''),
                    'NULL')
FROM    Market
GROUP BY Market.Name, Market.ID;

<强> Example on SQL Fiddle

注意我稍微更改了您的XML方法,因为仅使用(SELECT .. FOR XML PATH(''))会导致xml字符被转义(因此如果您在子查询中有>它会变为&gt;,但是,如果您使用'value方法,即保留FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX))个XML字符