如何检索非空&来自数据库的非重复数据?

时间:2018-06-16 07:25:59

标签: c# sql-server

我的桌子上有这个挑选的列(导致其余部分与问题无关)。

ID   | Generic Name
-----+---------------
001  | Cetirizine
002  | Cetirizine
003  |
004  | Paracetamol

我希望我的组合框只显示一个条目Cetirizine(或任何已复制的数据),并且没有空的通用名称(某些数据没有通用名称)。

我试过了:

select 
    Item_GenName 
from 
    ItemMasterlistTable 
where 
    nullif(convert(varchar, Item_GenName), '') is not null

但它只实现了无空数据部分。

我已尝试使用DISTINCT,但它不起作用且有人建议JOIN但我认为它不起作用,因为我只使用了1个表。

我也试过了:

SELECT 
    MIN(Item_ID) AS Item_ID, Item_GenName
FROM
    ItemMasterlistTable
GROUP BY 
    Item_GenName

但始终存在错误:

  

text,ntext和image数据类型无法进行比较或排序,除非使用IS NULL或LIKE运算符。

3 个答案:

答案 0 :(得分:2)

以下查询应仅返回不同的非空Item_GenNames:

SELECT DISTINCT Item_GenName
FROM ItemMasterlistTable
// because Item_GenName is of type *text*, the below in lieu of `is not null` and `!= ''`
WHERE datalength(Item_GenName) != 0

你说你试过DISTINCT而它没有用,所以我想澄清一下,

DISTINCT关键字将在select语句的完整域中返回唯一记录。如果在select语句中包含ID列,即使是不同的选择也会返回重复的Item_GenNames b / c,组合的ID / Item_GenName记录将是唯一的。在select子句中仅包含Item_GenName以保证此列的不同值。

答案 1 :(得分:1)

以下查询可能有用。

    declare @tab table (ID varchar(10), Generic_Name varchar(100))
    insert into @tab
    select '001',   'Cetirizine'
    union 
    select '002',   'Cetirizine'
    union 
    select '003',   ''
    union 
    select '004',   'Paracetamol'

    select MIN(substring(ID, 1, 10)) ID, substring(Generic_Name, 1, 1000) Generic_Name
from @tab
where substring(Generic_Name, 1, 1) <> ''
group by substring(Generic_Name, 1, 1000)

答案 2 :(得分:1)

您可以尝试此查询

Select  distinct Item_GenName FROM(
Select * FROM ItemMasterlistTable where Item_GenName <> ''
)t

内部查询删除非空记录,外部查询从内部输出中获取不同记录

相关问题