Hello all I have made a query using left outer joins which result in some what like the table below:
| 00-00-00-00-00 | 1 | a.txt | | 00-00-00-00-00 | 2 | b.txt | | 00-00-00-00-00 | 1 | c.txt | | 11-11-11-11-11 | 2 | d.txt |
What I want is Distict value of the MAC Column below is the SQL Fiddle to understand better.
Thanks
EDIT
The purpose is that 2 and 3 are useless or redundant data where as 1 and 4 are useful means the 1 and 4 show the current file on the MACs
Output:
| 00-00-00-00-00 | 1 | a.txt | | 11-11-11-11-11 | 2 | d.txt |
Is not possible to answer exactly what you ask. However, usually folk that express the question you ask really mean to ask something like 'I want all the columns for a sample of rows containing only distinct MacAddress values'. This question has many answers, as the result is non-deterministic. A trivial solution is to pick the first (for whatever definition of 'first') row for each MacAddress:
with cte as (
select row_number() over (partition by MacAddress order by CounterNo) as rn, *
from Heartbeats
)
select * from cte where rn = 1;
If you want to get only the distinct macaddresses, you can do:
SELECT DISTINCT macaddress FROM heartbeats
If you want all the columns alongside the distinct macaddress, you need to create a rule to get them. The query below gives you the ones with the highest id for each macaddress:
SELECT t1.*
FROM heartbeats t1
LEFT JOIN heartbeats t2
ON (t1.macaddress = t2.macaddress AND t1.id < t2.id)
WHERE t2.id IS NULL
EDIT:
Since in original query the code used doesnt have ID column the above query was refined as:
with cte as (
select ROW_NUMBER() OVER(ORDER BY (Select 0)) AS ID,* from heartBeats
)
SELECT t1.*
FROM cte t1
LEFT JOIN cte t2
ON (t1.macaddress = t2.macaddress AND t1.id < t2.id)
WHERE t2.id IS NULL
SELECT hb1.* FROM [heartbeats] as hb1
LEFT OUTER JOIN [heartbeats] as hb2
ON (hb1.macaddress = hb2.macaddress AND hb1.id > hb2.id)
WHERE hb2.id IS NULL;
You have to neglect the file name. See http://sqlfiddle.com/#!3/a75e47/13
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.