-1

数据库表“标签信息”

ID      Labels    
1       TRPKLM003 
2       JPRECM001 
3       MNTORM005 
4       JPRECM004 
5       MNTORM002 
6       JPRECM003 
7       TRPKLM002 
8       TRPKLM004 

列标签是固定长度的。我想返回以下数据作为结果:

TRPKLM004
MNTORM005
JPRECM004

我会编写一个访问查询,它可以通过对匹配的前 6 个字符和其余 3 个字符的最大值进行分组来仅返回行。或者如果我要返回表中的所有行,我想要一种优化的方法来过滤 C# 中的结果

4

1 回答 1

1

db 引擎可以拆分Labels字段的两个组件。

SELECT
    Left(Labels, 6) AS prefix_string
    Val(Right(Labels, 3)) AS suffix_nmbr
FROM LabelInfo;

将其用作查询的子GROUP BY查询。

SELECT
    sub.prefix_string,
    Max(sub.suffix_nmbr) AS MaxOfSuffix_nmbr
FROM
    (
        SELECT
            Left(Labels, 6) AS prefix_string
            Val(Right(Labels, 3)) AS suffix_nmbr
        FROM LabelInfo
    ) AS sub
GROUP BY sub.prefix_string;

如果在您的 c# 客户端代码中重新组合这两个部分不方便,您可以让 db 引擎将所有内容作为子查询来完成。

SELECT
    sub2.prefix_string
        & Format(sub2.MaxOfSuffix_nmbr, '000')
        AS labels_alias
FROM
    (
        SELECT
            sub1.prefix_string,
            Max(sub1.suffix_nmbr) AS MaxOfSuffix_nmbr
        FROM
            (
                SELECT
                    Left(Labels, 6) AS prefix_string
                    Val(Right(Labels, 3)) AS suffix_nmbr
                FROM LabelInfo
            ) AS sub1
        GROUP BY sub1.prefix_string
    ) AS sub2; 
于 2012-10-12T15:36:19.403 回答