最近在改报表分页,遇到一个很棘手的问题,需要将比较正常的数据记录新增加两列
第一列按照goodsid局部分组,然后在分组后的记录中按照audittime升序排序得到序号,从而显示某商品得第几次变迁。第二列是取该商品的最后变迁价格newPrice,然后将该值赋到这个商品的其他行中,例如对于goodsid为1的,最后一个newprice为20,那么对于所有goodsid为1的记录curprice都写为20,从而达到外面控件分布的效果。
如下,比较正常的数据记录:
以前的做法是在C#服务端将正常记录取出来(先按照GoodsId和audittime排序再取的),然后遍历整个数据集,新增了两个列,通过第一次循环解决expandfield的值问题,并用键值对巧妙的记录最后一次的newPrice,第二次循环则将键值对记录的newPrice赋给同一个goodsid的curprice。代码如下:
代码如下:
private void ChangeDataTable(DataTable dt)
{
dt.Columns.Add("curprice");
dt.Columns.Add("expandfield");
int goodsid = 0;
int index = 1; //指针
decimal curprice = 0;
IHashObject curpriceobj = new HashObject(); //键值对
//增加分布列
foreach(DataRow row in dt.Rows){
if (goodsid != Convert.ToInt32(row["goodsid"])) {
curpriceobj.Add("goodsid_"+goodsid, curprice);
//处理
index = 0;
goodsid = Convert.ToInt32(row["goodsid"]);
}
curprice = Convert.ToDecimal(row["newprice"]);
index += 1;
row["expandfield"] = "第" + index + "次变迁";
}
if(dt.Rows.Count != 0){ //添加最后一个商品的现行价
curpriceobj.Add("goodsid_"+goodsid, curprice);
}
//增加现行价
foreach (DataRow row in dt.Rows) {
row["curprice"] = curpriceobj["goodsid_" + row["goodsid"]];
}
}
但现在报表存储过程必须分页,分页后还要支持排序,如果客户端要求按照最新价格newPrice排序,很明显这样通过服务端转换的数据源是没办法支持的(因为在数据库分页前的数据源并没有newPrice这个字段)。
另外在C#服务端处理,其实是比较占内存的,其一对DataTable遍历了两次,另外还用了临时键值对对象,反复赋值是有性能消耗。
综上所述,最终我选择放在数据库来构建这两列。
关于第一列局部排序,我很快想到了一个以前看过的语法 ROW_NUMBER() OVER(PARTITION BY...ORDER BY),于是第一列expandfield很容易就构建了,SQL如下:
代码如下:
SELECT '第' + CAST(ROW_NUMBER() OVER(PARTITION BY GoodsId ORDER BY audittime DESC) AS VARCHAR(10)) + '次变迁' AS expandfield,
GoodsId, price , discount , newPrice , begindate as [date]
FROM #test
但真正麻烦的是第二列,我抠破脑壳来想都没想出来,甚至想到用临时表来记录这个结果集,然后用游标来遍历结果集,update这个表来修改记录,但还是感觉相当的繁琐,而且性能很差。后来我请教了下公司的DBA,她给出了一种思路,这种方案无论从效率还是可行性都是最优的。先贴出代码如下:
代码如下:
WITH _TEMP AS (
SELECT ROW_NUMBER() OVER ( PARTITION BY GoodsId ORDER BY audittime DESC ) AS num2 ,
ROW_NUMBER() OVER ( PARTITION BY GoodsId ORDER BY audittime ) AS num ,
GoodsId, price , discount , newPrice , begindate as [date]
FROM #test
)
SELECT '第' + CAST(a.num AS VARCHAR(10)) + '次变迁' AS expandfield ,
a.goodsid , a.price , a.discount , a.newprice , a.date , b.newprice AS curprice
FROM _TEMP a
INNER JOIN _TEMP b ON a.GoodsId = b.GoodsId AND b.num2 = 1
这里用了一个CTE表达式的自关联查询,从性能上说是很有优势的,相对于临时表减少了对tempdb的开销,另外代码的可读性也比嵌套查询更强,num列是用来构建第几次变迁列的,这里很巧妙得多加了按照audittime降序列的num2列,在下面临时记录b中,通过指定b.num2 = 1取得所有goodsid最后变价的记录,再通过一个INNER JOIN就得到了我们想要的值curprice值。
另外补充一下,像上面存在多个列上排序字段时,SQL会选择后者进行重排,即先按goodsid分组,然后再各个组中按audittime升序排列,如果将num放在前,num2放在后,是得不到我们要的记录。

InnoDBBufferPool reduces disk I/O by caching data and indexing pages, improving database performance. Its working principle includes: 1. Data reading: Read data from BufferPool; 2. Data writing: After modifying the data, write to BufferPool and refresh it to disk regularly; 3. Cache management: Use the LRU algorithm to manage cache pages; 4. Reading mechanism: Load adjacent data pages in advance. By sizing the BufferPool and using multiple instances, database performance can be optimized.

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

MySQL is worth learning because it is a powerful open source database management system suitable for data storage, management and analysis. 1) MySQL is a relational database that uses SQL to operate data and is suitable for structured data management. 2) The SQL language is the key to interacting with MySQL and supports CRUD operations. 3) The working principle of MySQL includes client/server architecture, storage engine and query optimizer. 4) Basic usage includes creating databases and tables, and advanced usage involves joining tables using JOIN. 5) Common errors include syntax errors and permission issues, and debugging skills include checking syntax and using EXPLAIN commands. 6) Performance optimization involves the use of indexes, optimization of SQL statements and regular maintenance of databases.

MySQL is suitable for beginners to learn database skills. 1. Install MySQL server and client tools. 2. Understand basic SQL queries, such as SELECT. 3. Master data operations: create tables, insert, update, and delete data. 4. Learn advanced skills: subquery and window functions. 5. Debugging and optimization: Check syntax, use indexes, avoid SELECT*, and use LIMIT.

MySQL efficiently manages structured data through table structure and SQL query, and implements inter-table relationships through foreign keys. 1. Define the data format and type when creating a table. 2. Use foreign keys to establish relationships between tables. 3. Improve performance through indexing and query optimization. 4. Regularly backup and monitor databases to ensure data security and performance optimization.

MySQL is an open source relational database management system that is widely used in Web development. Its key features include: 1. Supports multiple storage engines, such as InnoDB and MyISAM, suitable for different scenarios; 2. Provides master-slave replication functions to facilitate load balancing and data backup; 3. Improve query efficiency through query optimization and index use.

SQL is used to interact with MySQL database to realize data addition, deletion, modification, inspection and database design. 1) SQL performs data operations through SELECT, INSERT, UPDATE, DELETE statements; 2) Use CREATE, ALTER, DROP statements for database design and management; 3) Complex queries and data analysis are implemented through SQL to improve business decision-making efficiency.

The basic operations of MySQL include creating databases, tables, and using SQL to perform CRUD operations on data. 1. Create a database: CREATEDATABASEmy_first_db; 2. Create a table: CREATETABLEbooks(idINTAUTO_INCREMENTPRIMARYKEY, titleVARCHAR(100)NOTNULL, authorVARCHAR(100)NOTNULL, published_yearINT); 3. Insert data: INSERTINTObooks(title, author, published_year)VA


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version
God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download
The most popular open source editor