0

我正在尝试从列中选择不同的值,但返回与所选值相关的所有行。在伪代码中,它看起来像这样。

SELECT * 
FROM table
WHERE field is Distinct 

我用谷歌搜索了这个问题,我试过使用 GROUP BY 但查询永远不会执行。谢谢您的帮助。

我正在使用 Microsoft SQL 数据库。

数据如下所示:

CodeId   Code   CatalogType    CodeGroup  CodeText  CodeGroupText  CodeDesc  State_ID
-------  -----  -------------  ---------- --------  -------------- --------- ---------
1        AAAA    1             100         Plastic   Plastic Center  NULL      2
2        BBBB    1             100         Glass     Glass Center    NULL      2
3        CCCC    1             101         Steel     Steel Center    NULL      2

我只想让数据在代码组不同的地方看起来相同。

数据如下所示:

CodeId   Code   CatalogType    CodeGroup  CodeText  CodeGroupText  CodeDesc  State_ID
-------  -----  -------------  ---------- --------  -------------- --------- ---------
1        AAAA    1             100         Plastic   Plastic Center  NULL      2
3        CCCC    1             101         Steel     Steel Center    NULL      2
4

4 回答 4

3

在大多数数据库中,您可以执行以下操作:

select t.*
from (select t.*
             row_number() over (partition by field order by field) as seqnum
      from t
     ) t
where seqnum = 1
于 2013-07-02T19:51:30.933 回答
3

您始终可以使用子查询来返回min(codeid)for eachcodegroup并将此结果连接到您的表中:

select t1.codeid,
    t1.code,
    t1.catalogtype,
    t1.codegroup,
    t1.codetext,
    t1.codegrouptext,
    t1.codedesc,
    t1.state_id
from yourtable t1
inner join
(
    select MIN(codeid) codeid, codegroup
    from yourtable
    group by codegroup
) t2
    on t1.codeid = t2.codeid
    and t1.codegroup = t2.codegroup
于 2013-07-02T20:11:24.277 回答
0
SELECT field1,field2,max(field3),sum(field4)
FROM table
GROUP BY field1, field2

这将为您提供所有不同的 field1 和 field2。您无法直接获取 field3 字段(使用此分组),因为可能有多个 field3。

于 2013-07-02T19:52:51.757 回答
0

如果您只需要列中的不同值,即在一个列中找到一组唯一值,那么这段代码可以帮助您(至少对于 sql server):

select distinct
    columnName
from tableT
于 2013-07-02T19:54:16.710 回答