简体   繁体   中英

How to get unique value from SQL Server in C#

I want to select distinct value in the query but it shows multiple values. I have 2 identical names in my name column. I think distinct is for unique value but I don't know what is happening.

Here is my query

string lakhas1 = "SELECT DISTINCT
NAME,EXPENSE,AMOUNT1,AMOUNT2,AMOUNT3,AMOUNT01,AMOUNT02,AMOUNT03 FROM
INCOME ORDER BY NAME";
DataTable dt1 = DataAccess.GetDataTable(lakhas1);

In order to have your result set be distinct by name , you can use the group by keyword to group the records. When you do this, any other columns you want to select either have to be part of the group by (ie part of the key that makes the record distinct) or they have to be used in an aggregate function.

In this case, I assumed you want to sum the values from the records together. However, you could use min() or max() just the same.

select
    name,
    sum(expense) as expense,
    sum(amount1) as amount1,
    sum(amount2) as amount2,
    sum(amount3) as amount3,
    sum(amount01) as amount01,
    sum(amount02) as amount02,
    sum(amount03) as amount03
from dbo.income
group by name
order by name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM