0

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

市场表:

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' 返回?

4

1 回答 1

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;

SQL Fiddle 示例

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

于 2013-10-08T12:28:53.050 回答