使用SQL

时间:2017-12-08 12:16:48

标签: sql sql-server xml

我想在嵌套XML元素的底部包含一行“Frequency”。目前,我的代码将频率线放在返回部分之外。我希望它出现在它里面,作为底部的一行。我有下面的代码几乎就在那里。还显示了电流输出和所需输出:

SELECT
    (SELECT  
    'USD' AS 'Currency',   
    'TestDatabase' AS 'Datasource',
    'Test Name' AS 'Name',
            (SELECT
            ValueDate AS 'Date',
            ReturnValue AS 'ROR'
            FROM FactReturn [Value]
            WHERE [Value].AssetId = asset.AssetId
            FOR XML AUTO,TYPE, ROOT('Returns')),
     'Daily' AS 'Frequency'
     FROM DimAsset Asset
     FOR XML AUTO, ELEMENTS, TYPE, ROOT('Assets'))
FOR  XML PATH('Body'),ROOT('ASPackage')

结果:

Current Result

期望的结果:

Desired Result

1 个答案:

答案 0 :(得分:0)

我要求您提供一些带有适当样本数据的最小化表格。我在下次使用模型对象设置测试场景时所做的工作应该是你的工作......

试试这样:

DECLARE @DimAssetMockup TABLE(AssetID INT,AssesName VARCHAR(100));
INSERT INTO @DimAssetMockup VALUES(1,'Asset 1'),(2,'Asset 2');

DECLARE @FactReturnMockup TABLE(AssetID INT,ValueDate DATETIME, ReturnValue DECIMAL(12,10))
INSERT INTO @FactReturnMockup VALUES(1,{d'2017-01-01'},0.11)
                                   ,(1,{d'2017-01-02'},0.12)
                                   ,(2,{d'2017-02-01'},0.21)
                                   ,(2,{d'2017-02-02'},0.22);

SELECT
(
    SELECT 'USD' AS 'Currency'
          ,'TestDatabase' AS 'Datasource'
          ,AssesName AS [Name]
          ,(
            SELECT [Value].ValueDate AS [@Date]
                  ,[Value].ReturnValue as [@ROR]
            FROM @FactReturnMockup AS [Value]
            WHERE [Value].AssetID=Asset.AssetID
            FOR XML PATH('Value'),TYPE
           ) AS [Returns]
          ,'Daily' AS [Returns/Frequency]
    FROM @DimAssetMockup Asset
    FOR XML PATH('Asset'),ROOT('Assets'),TYPE
)
FOR XML PATH('Body'),ROOT('ASPackage');

结果

<ASPackage>
  <Body>
    <Assets>
      <Asset>
        <Currency>USD</Currency>
        <Datasource>TestDatabase</Datasource>
        <Name>Asset 1</Name>
        <Returns>
          <Value Date="2017-01-01T00:00:00" ROR="0.1100000000" />
          <Value Date="2017-01-02T00:00:00" ROR="0.1200000000" />
          <Frequency>Daily</Frequency>
        </Returns>
      </Asset>
      <Asset>
        <Currency>USD</Currency>
        <Datasource>TestDatabase</Datasource>
        <Name>Asset 2</Name>
        <Returns>
          <Value Date="2017-02-01T00:00:00" ROR="0.2100000000" />
          <Value Date="2017-02-02T00:00:00" ROR="0.2200000000" />
          <Frequency>Daily</Frequency>
        </Returns>
      </Asset>
    </Assets>
  </Body>
</ASPackage>