简体   繁体   English

sql查询以基于特定列填充具有多个数据表的数据集

[英]sql query to fill dataset with multiple datatables based on specific column

I have a SQL Server table called tSongList that contains the following information: 我有一个名为tSongList的SQL Server表,其中包含以下信息:

colAlbumID, colSongName, colAlbumTrackNumber, colRequestedCount, colPlayPriority

The purpose of this table is to help a DJ keep a list of which songs the DJ should play and which album they are from. 这张桌子的目的是帮助DJ记录DJ应该播放哪些歌曲以及它们来自哪个专辑。 I have a C# class that will take a list of songs from a specific albumID and calculate the colPlayPriority based on the colRequestedCount . 我有一个C#类,它将从特定的albumID歌曲列表,并根据colPlayPriority计算colRequestedCount I have designed this class to take a DataTable containing the columns above and compute the necessary information. 我设计了这个类来获取包含上面列的DataTable并计算必要的信息。

So my question is if I want to use SQL to select all the rows from the tSongList , how do I get the SQL result into multiple DataTables grouped by colAlbumID ? 所以我的问题是如果我想使用SQL从tSongList选择所有行,我如何将SQL结果转换为按colAlbumID分组的多个DataTables In other words, I want a DataTable for each Album that contains it's song information. 换句话说,我想为每个包含它的歌曲信息的专辑提供一个DataTable

I know that I can use a SqlDataAdapter to fill a DataSet and since a DataSet can contain multiple DataTables , is there a way to construct a SQL query to return a DataSet containing the DataTables grouped by albumID ? 我知道我可以使用SqlDataAdapter来填充DataSet并且由于DataSet可以包含多个DataTables ,有没有办法构造SQL查询以返回包含按albumID分组的DataTablesDataSet

Also if this can't be done, should I just select everything into one DataTable and use the Select function to get a DataRow array instead? 此外,如果无法做到这一点,我应该只选择一个DataTable并使用Select函数来获取DataRow数组吗?

One option is to return a single DataTable and use LINQ to create your grouping. 一种选择是返回单个DataTable并使用LINQ创建分组。

var albumGroups = from a in dtAlbums.AsEnumerable()
  group a by a.Field<int>("albumID") into g
  select new { colSongName = g.Field<string>("colSongName"), 
               colAlbumTrackNumber = g.Field<int>("colAlbumTrackNumber"),
               colRequestedCount = g.Field<int>("colRequestedCount"),
               colPlayPriority = g.Field<int>("colPlayPriority") };

I think the example on MSDN will show you how to do this. 我想MSDN上的例子会告诉你如何做到这一点。 You will make life much easier for yourself if you properly normalise your data first. 如果您首先正确地规范化数据,您将使自己的生活更轻松。 You can create a hierarchical DataSet with the necessary relationships in place making it trivial to get all songs for an album. 您可以创建一个具有必要关系的分层DataSet,这样可以轻松获取专辑的所有歌曲。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM