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

MySQL'sBLOBissuitableforstoringbinarydatawithinarelationaldatabase,whileNoSQLoptionslikeMongoDB,Redis,andCassandraofferflexible,scalablesolutionsforunstructureddata.BLOBissimplerbutcanslowdownperformancewithlargedata;NoSQLprovidesbetterscalabilityand

ToaddauserinMySQL,use:CREATEUSER'username'@'host'IDENTIFIEDBY'password';Here'showtodoitsecurely:1)Choosethehostcarefullytocontrolaccess.2)SetresourcelimitswithoptionslikeMAX_QUERIES_PER_HOUR.3)Usestrong,uniquepasswords.4)EnforceSSL/TLSconnectionswith

ToavoidcommonmistakeswithstringdatatypesinMySQL,understandstringtypenuances,choosetherighttype,andmanageencodingandcollationsettingseffectively.1)UseCHARforfixed-lengthstrings,VARCHARforvariable-length,andTEXT/BLOBforlargerdata.2)Setcorrectcharacters

MySQloffersechar, Varchar, text, Anddenumforstringdata.usecharforfixed-Lengthstrings, VarcharerForvariable-Length, text forlarger text, AndenumforenforcingdataAntegritywithaetofvalues.

Optimizing MySQLBLOB requests can be done through the following strategies: 1. Reduce the frequency of BLOB query, use independent requests or delay loading; 2. Select the appropriate BLOB type (such as TINYBLOB); 3. Separate the BLOB data into separate tables; 4. Compress the BLOB data at the application layer; 5. Index the BLOB metadata. These methods can effectively improve performance by combining monitoring, caching and data sharding in actual applications.

Mastering the method of adding MySQL users is crucial for database administrators and developers because it ensures the security and access control of the database. 1) Create a new user using the CREATEUSER command, 2) Assign permissions through the GRANT command, 3) Use FLUSHPRIVILEGES to ensure permissions take effect, 4) Regularly audit and clean user accounts to maintain performance and security.

ChooseCHARforfixed-lengthdata,VARCHARforvariable-lengthdata,andTEXTforlargetextfields.1)CHARisefficientforconsistent-lengthdatalikecodes.2)VARCHARsuitsvariable-lengthdatalikenames,balancingflexibilityandperformance.3)TEXTisidealforlargetextslikeartic

Best practices for handling string data types and indexes in MySQL include: 1) Selecting the appropriate string type, such as CHAR for fixed length, VARCHAR for variable length, and TEXT for large text; 2) Be cautious in indexing, avoid over-indexing, and create indexes for common queries; 3) Use prefix indexes and full-text indexes to optimize long string searches; 4) Regularly monitor and optimize indexes to keep indexes small and efficient. Through these methods, we can balance read and write performance and improve database efficiency.


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

Dreamweaver Mac version
Visual web development tools

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

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

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.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
