Reputation: 1295
I have a table called AssetTable
which stores AssetId
I have another table called AssetBookTable
which stores two fields BookId and CurrentOperationsTax
Another table AssetBook
that stores AssetId and BookId as foriegn keys.
Now, I have a situation in which I have to filter records based on AssetBookTable.CurrentOperationsTax
This, is what I am getting now,
And this, is what I want:
**
The logic is that I want only one BookId per AssetId that has either Current/Operation/Tax for CurrentOperationsTax field.
**
Here's the SQL fiddle written so far:
Any help is greatly appreciated.
Upvotes: 2
Views: 105
Reputation: 923
I prefer using the ROW_NUMBER approach. It does require the use of a subquery. In summary it is grouping the records by the CuurentOperationsTax number and ordering by book id and giving the row number for each grouping. Then in the outer select I filter out how many I want for each grouping. In this example just 1.
SELECT AssetId
,BookId
,CuurentOperationsTax
,RowNum
FROM (
SELECT
ab.AssetId
,ab.BookId
,abt.CuurentOperationsTax
,ROW_NUMBER() OVER(PARTITION BY abt.CuurentOperationsTax ORDER BY ab.BookId) AS RowNum
FROM
AssetBook ab
JOIN AssetTable AT ON AT.AssetId = ab.AssetId
JOIN AssetBookTable abt ON abt.BookId = ab.BookId
) AS b
WHERE b.RowNum = 1
Upvotes: 1
Reputation: 20909
You can simple remove the GROUP BY BookID
. But of course you then need to aggregate the BookID some how. Here using the MIN() function:
SELECT
ab.AssetId
,MIN(ab.BookId) as BookID
,abt.CuurentOperationsTax
FROM
AssetBook ab
JOIN AssetTable at ON at.AssetId = ab.AssetId
JOIN AssetBookTable abt ON abt.BookId = ab.BookId
GROUP BY
ab.AssetId
,abt.CuurentOperationsTax
http://sqlfiddle.com/#!6/e3477/42
Upvotes: 1