使用查询加入许多表

时间:2017-06-07 13:03:00

标签: mysql sql database

当Restaurantid = StoreID时,我想在第一次查询时添加Count(Taskid)和Count(Complete)。但我不知道如何制作一个查询来制作一个表。有什么想法吗?

 private DataTable GetData() //get any data from database SeongsilApp
{
    string connString = @"aa.net;Initial Catalog=db_c;Persist Security Info=True;User ID=db_c_ExternalWriter;Password=aa";
    string query = "Select a.Name, b.Restaurant,  a.City, c.[Postal Code], a.[Open Date], a.POSSystem as 'Taskid' FROM Stores a, tblConcepts b, tblStates c WHERE a.ConceptID = b.Restaurantid AND  a.State = c.Stateid AND a.[Open Date] >= cast(cast(getdate() as date) as datetime)";
    string query2 = "SELECT StoreID, Count(Taskid) FROM tblAssignedTasks WHERE Complete = 'True' GROUP BY StoreID";
    string query3 = "SELECT StoreID, Count(Complete) FROM tblAssignedTasks WHERE TargetDate <= cast(cast(getdate() as date) as datetime) AND Complete = 'True' GROUP BY StoreID";


    DataTable dt = new DataTable();
    using (SqlConnection con = new SqlConnection(connString))
    {
        using (SqlCommand comm = new SqlCommand(query))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                comm.Connection = con;
                sda.SelectCommand = comm;
                    sda.Fill(dt);
                    return dt;
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您可以编写内部SELECT查询以获取计数以及主查询。另外,对于JOIN,最好使用ON语法而不是在WHERE子句中指定条件,例如:

Select a.Name, b.Restaurant,  a.City, c.[Postal Code], a.[Open Date], a.POSSystem as 'Taskid',
(SELECT Count(Taskid) FROM tblAssignedTasks WHERE Complete = 'True' AND StoreID = b.Restaurantid) AS `completed`,
(SELECT Count(Complete) FROM tblAssignedTasks WHERE TargetDate <= cast(cast(getdate() as date) as datetime) AND Complete = 'True' AND StoreID = b.Restaurantid) AS `target`
FROM Stores a JOIN tblConcepts b ON a.ConceptID = b.Restaurantid
JOIN tblStates c ON a.State = c.Stateid 
WHERE a.[Open Date] >= cast(cast(getdate() as date) as datetime)