巧妙的自关联运用
最近在改报表分页,遇到一个很棘手的问题,需要将比较正常的数据记录新增加两列
第一列按照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放在后,是得不到我们要的记录。

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics











The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

InnoDB uses redologs and undologs to ensure data consistency and reliability. 1.redologs record data page modification to ensure crash recovery and transaction persistence. 2.undologs records the original data value and supports transaction rollback and MVCC.

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

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 suitable for small and large enterprises. 1) Small businesses can use MySQL for basic data management, such as storing customer information. 2) Large enterprises can use MySQL to process massive data and complex business logic to optimize query performance and transaction processing.

MySQL index cardinality has a significant impact on query performance: 1. High cardinality index can more effectively narrow the data range and improve query efficiency; 2. Low cardinality index may lead to full table scanning and reduce query performance; 3. In joint index, high cardinality sequences should be placed in front to optimize query.

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

MySQL is suitable for web applications and content management systems and is popular for its open source, high performance and ease of use. 1) Compared with PostgreSQL, MySQL performs better in simple queries and high concurrent read operations. 2) Compared with Oracle, MySQL is more popular among small and medium-sized enterprises because of its open source and low cost. 3) Compared with Microsoft SQL Server, MySQL is more suitable for cross-platform applications. 4) Unlike MongoDB, MySQL is more suitable for structured data and transaction processing.
