c# - C#查询两个数据库的数据

标签 c# sql asp.net sql-server asp.net-mvc

我目前有一个查询,我从 2 个不同的数据库中获取数据,这些数据被附加到一个名为“accountbuys”的列表中。

  1. 我的第一个表有三个数据条目(3个账户要买股票

  2. 下表有 17 个数据点(17 只股票要买)

我正在合并这些表并获得输出 enter image description here

但是,我想要的输出应该对 3 个不同的帐户每次重复 17 个数据点,以便最终用户可以向下钻取并购买他想要的任何股票 enter image description here

PS:如果我想问的不清楚,请礼貌地告诉我。请尽量不要粗鲁,我仍在学习,并且是 StackExchange 的新手!

这是我的代码:`

public List<BuySellModel> GetBuyDataWthAccount()
{
    List<BuySellModel> accountbuys = new List<BuySellModel>();

    using (SqlConnection connectionreit = new SqlConnection(HubConnection))
    using (SqlConnection connection = new SqlConnection(PMConnection))

    {

        connectionhub.Open();
        connection.Open();

        SqlCommand command3 = new SqlCommand(@"SELECT distinct(table1.name) as 'Symbol' ,table2.Segment as 'Segment',table2.AllocationAmount as 'AllocationAmount',table2.PX_LAST as 'Price', 
                                                    table1.CUR_MKT_CAP as 'CMC',table1.FCFY_WITH_CUR_MKT_CAP as 'FCMC',table1.ROIC as 'ROIC', table1.ROICDELTA as 'ROICD' FROM View_REIT_Model_And_Holdings as table1
                                                    INNER JOIN [MostRecentlyInModelSelected] as table2
                                                        ON table1.name = table2.Ticker
                                                        WHERE table1.AllocationAmount != -1 AND
                                                        NOT EXISTS (SELECT NULL FROM [ViewPCData] as table3 WHERE table1.name = table3.Symbol AND table2.Segment = table3.SubsectorDescription AND table3.Objective = 'REITS' AND table3.SectorDescription != 'NULL' AND table3.SubsectorDescription != 'NULL')",
                                                    connectionreit);
        command3.CommandType = CommandType.Text;

        SqlCommand command4 = new SqlCommand("SELECT PortfolioAccountNumber, PortfolioDescription, SUM(TotalValue) as 'TotalValue' FROM [ViewPCData] WHERE Objective = 'REITS' GROUP BY PortfolioAccountNumber,PortfolioDescription", connection);
        command4.CommandType = CommandType.Text;

        var reader = command3.ExecuteReader();
        var reader1 = command4.ExecuteReader();

        if (reader1.HasRows)
        {
            while (reader1.Read())
            {
                BuySellModel accountb = new BuySellModel();
                accountb.PortfolioAccount = reader1.GetString(reader1.GetOrdinal("PortfolioAccountNumber"));
                accountb.PortfolioDescription = reader1.GetString(reader1.GetOrdinal("PortfolioDescription"));
                accountb.AccountAmount = reader1.GetDecimal(reader1.GetOrdinal("TotalValue"));
                accountbuys.Add(accountb);

                if (reader.HasRows)
                {
                    //foreach(var account in accountbuys)
                    //{


                    while (reader.Read())
                    {
                        BuySellModel buy = new BuySellModel();
                        buy.Symbol = reader.GetString(reader.GetOrdinal("Symbol"));
                        buy.Segment = reader.GetString(reader.GetOrdinal("Segment"));
                        //if (accountNumber == "soand os")
                        //{
                        //    1/3 of totalaccountvalue
                        buy.AllocationAmount = (reader.GetDouble(reader.GetOrdinal("AllocationAmount")));
                        //}
                        buy.Price = reader.GetDouble(reader.GetOrdinal("Price"));
                        buy.MarketValue = reader.GetDouble(reader.GetOrdinal("CMC"));
                        buy.FCFY = reader.GetDouble(reader.GetOrdinal("FCMC"));
                        buy.ROIC = reader.GetDouble(reader.GetOrdinal("ROIC"));
                        buy.ROICdelta = reader.GetDouble(reader.GetOrdinal("ROICD"));
                        buy.Buy = true;
                        //account1 = account.accountnumber;                   
                        accountbuys.Add(buy);

                    }
                    //} //for loop


                }


            } // accounts
        } //reader1.hasrows

        connectionhub.Close();
        connection.Close();
    }

    return accountbuys;
}

编辑:

将表格拆分为两个不同的列表,稍后再将它们合并。这现在运作良好。似乎也适合缩放。

public List<BuySellModel> GetBuyDataWthAccount()
    {
        List<BuySellModel> accountbuys = new List<BuySellModel>();

        List<Account> accounts = new List<Account>();


        using (SqlConnection connection = new SqlConnection(PMConnection))

        {

            connection.Open();

            SqlCommand command3 = new SqlCommand(@"SELECT distinct(table1.name) as 'Symbol' ,table2.Segment as 'Segment',table2.AllocationAmount as 'AllocationAmount',table2.PX_LAST as 'Price', 
                                                table1.CUR_MKT_CAP as 'CMC',table1.FCFY_WITH_CUR_MKT_CAP as 'FCMC',table1.ROIC as 'ROIC', table1.ROICDELTA as 'ROICD' FROM View_Model_And_Holdings as table1
                                                INNER JOIN [MostRecentlyInModelSelected] as table2
                                                    ON table1.name = table2.Ticker
                                                    WHERE table1.AllocationAmount != -1 AND
                                                    NOT EXISTS (SELECT NULL FROM [ViewPCData] as table3 WHERE table1.name = table3.Symbol AND table2.Segment = table3.SubsectorDescription AND table3.Objective = 'STOCKS' AND table3.SectorDescription != 'NULL' AND table3.SubsectorDescription != 'NULL')",
                                                connectionreit);
          command3.CommandType = CommandType.Text;

          SqlCommand command4 = new SqlCommand("SELECT PortfolioDetail , SUM(TotalValue) as 'TotalValue' FROM [ViewPCData] WHERE Objective = 'STOCKS' GROUP BY PortfolioAccountNumber,PortfolioDescription", connection);
          command4.CommandType = CommandType.Text;

            var reader = command3.ExecuteReader();
            var reader1 = command4.ExecuteReader();
            if (reader1.HasRows)
            {
                while (reader1.Read())
                {
                    Account accountb = new Account();
                    accountb.PortfolioDetail = reader1.GetString(reader1.GetOrdinal("PortfolioDetail"));
                   // accountb.PortfolioDescription = reader1.GetString(reader1.GetOrdinal("PortfolioDescription"));
                    accountb.AccountAmount = reader1.GetDecimal(reader1.GetOrdinal("TotalValue"));

                    accounts.Add(accountb);
                }
            }
            //List<BuyReits> buys = new List<BuyReits>();
            if (reader.HasRows && accounts.Count > 0)
            {
                while (reader.Read())
                {
                    foreach (var acc in accounts)
                    {
                        BuySellModel buy = new BuySellModel();
                        buy.Symbol = reader.GetString(reader.GetOrdinal("Symbol"));
                        buy.Segment = reader.GetString(reader.GetOrdinal("Segment"));
                        buy.AllocationAmount = (reader.GetDouble(reader.GetOrdinal("AllocationAmount")));
                        buy.Price = reader.GetDouble(reader.GetOrdinal("Price"));
                        //buy.Quantity = reader.GetInt32((reader.GetOrdinal("AllocationAmount"))/(reader.GetOrdinal("Price")));
                        buy.MarketValue = reader.GetDouble(reader.GetOrdinal("CMC"));
                        buy.FCFY = reader.GetDouble(reader.GetOrdinal("FCMC"));
                        buy.ROIC = reader.GetDouble(reader.GetOrdinal("ROIC"));
                        buy.ROICdelta = reader.GetDouble(reader.GetOrdinal("ROICD"));
                        buy.Buy = true;
                        buy.PortfolioAccount = acc.PortfolioDetail;
                        buy.AccountAmount = acc.AccountAmount;

                        accountbuys.Add(buy);

                    }

                }
            }

            connection.Close();


        }

        return accountbuys;

    }

最佳答案

以下提供了 C# 层中的交叉连接(并不是说这是最好的解决方案,但它让您更接近准备就绪):

using (SqlConnection connectionhub = new SqlConnection(HubConnection))
using (SqlConnection connection = new SqlConnection(PMConnection))

{

    connectionhub.Open();
    connection.Open();

    SqlCommand command3 = new SqlCommand(@"
        SELECT distinct(table1.name) as 'Symbol',
               table2.Segment as 'Segment',
               table2.AllocationAmount as 'AllocationAmount',
               table2.PX_LAST as 'Price', 
               table1.CUR_MKT_CAP as 'CMC',
               table1.FCFY_WITH_CUR_MKT_CAP as 'FCMC',
               table1.ROIC as 'ROIC', 
               table1.ROICDELTA as 'ROICD' 
          FROM View_REIT_Model_And_Holdings as table1
                INNER JOIN [MostRecentlyInModelSelected] as table2
                    ON table1.name = table2.Ticker
         WHERE table1.AllocationAmount != -1 
           AND NOT EXISTS (SELECT NULL 
                             FROM [ViewPCData] as table3 
                            WHERE table1.name = table3.Symbol 
                              AND table2.Segment = table3.SubsectorDescription 
                              AND table3.Objective = 'REITS' 
                              AND table3.SectorDescription != 'NULL' 
                              AND table3.SubsectorDescription != 'NULL')",
                                                connectionreit);
    command3.CommandType = CommandType.Text;

    SqlCommand command4 = new SqlCommand(@"
        SELECT PortfolioAccountNumber, 
               PortfolioDescription, 
               SUM(TotalValue) as 'TotalValue' 
          FROM [ViewPCData] 
         WHERE Objective = 'REITS' 
         GROUP BY PortfolioAccountNumber, PortfolioDescription", connection);
    command4.CommandType = CommandType.Text;

    var stocksDS = new DataSet();
    var stocksDA = new System.Data.SqlClient.SqlDataAdapter();
    stocksDA.SelectCommand = command3
    stocksDA.Fill(stocksDS, "stocks");

    var acctsDS = new DataSet();
    var acctsDA = new System.Data.SqlClient.SqlDataAdapter();
    acctsDA.SelectCommand = command4
    acctsDA.Fill(acctsDS, "accts");

    var stocks = stocksDS.Tables["stocks"].AsEnumerable();
    var accts = acctsDS.Tables["accts"].AsEnumerable();

    var results = (from stocksDR in stocks
                   from acctsDR in accts
                   select new BuySellModel {
                        PortfolioAccount = acctsDR["PortfolioAccountNumber"],
                        PortfolioDescription = acctsDR["PortfolioAccountDescription"],
                        AccountAmount = acctsDR["TotalValue"],
                        Symbol = stocksDR["Symbol"],
                        Segment = stocksDR["Segment"],
                        AllocationAmount = stocksDR["AllocationAmount"],
                        Price = stocksDR["Price"],
                        MarketValue = stocksDR["CMC"],
                        FCFY = stocksDR["FCMC"],
                        ROIC = stocksDR["ROIC"],
                        ROICdelta = stocksDR["ROICD"],
                        Buy = true
                    });

    foreach (BySellModel buy in results) {
        accountBuys.Add(buy);
    }

    connectionhub.Close();
    connection.Close();
}

编辑:删除了有问题的括号。

关于c# - C#查询两个数据库的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43458171/

相关文章:

javascript - 每次刷新时从内部更新面板执行 javascript

asp.net - 检查 ViewState 中的值

c# - 从代码隐藏向 JavaScript 函数传递参数

c# - 用于屏幕文本的 OCR(光学字符识别)

MySQL:选择两个数据库中时间戳不匹配的所有行

java - getSelectedItem().toString() 返回 null 值

mysql - 具有多个 where 条件的 SQL 多重选择

javascript - 是否可以在 Javascript 的 Telerik RadDropDownList 中设置选定值?

c# - 项目从VS2010迁移到VS2012后无法继承接口(interface)

c# - 保存当前窗口 URL 并在几次导航后移回该 URL