2

I have data like these:

name_text   ----------c_num---d_type-----unique_id----------------------v_text--r_ticket_id
29311875_FAD_V100.doc 3560709 Contract 21DABDDF49BA41289F1905D1D6B79ABF 2,01    28600206
29311875_FAD_V100.doc 3560709 Contract 21DABDDF49BA41289F1905D1D6B79ABF 2,01    28600240
Copy.docx             3560715 Guide    9D06F8EFF4EC4A2D862F5A0DB3BA357B 2       28600219

I want to select just one row which has the bigger value of r_ticket_id column, if name_text, c_num, d_type, unique_id, v_text columns values are equal.

In these case, with select statement just this columns should be fetched.

name_text   ----------c_num---d_type-----unique_id----------------------v_text--r_ticket_id
29311875_FAD_V100.doc 3560709 Contract 21DABDDF49BA41289F1905D1D6B79ABF 2,01    28600240
Copy.docx             3560715 Guide    9D06F8EFF4EC4A2D862F5A0DB3BA357B 2       28600219

What is the exact SQL query that will do this job?

1
  • are there any possibilities that a record may have same unique id but have different values on every column? Commented Oct 21, 2012 at 14:48

2 Answers 2

5

This may be helpful when a record may have the same unique id but have different values on every column. Make use of ROW_NUMBER and window function. I guess they are already present on sql-server 2005.

SELECT name_text,c_num,d_type,unique_id,v_text,r_ticket_id
FROM
    (
        SELECT  name_text, c_num, d_type, unique_id, v_text, r_ticket_id,
                ROW_NUMBER() OVER (PARTITION BY unique_id 
                                   ORDER BY r_ticket_id DESC) rn
        FROM tableName
    ) x
WHERE x.rn = 1

SQLFiddle Demo

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for this reasonable and instructive answer.
2

In SQL, we have GROUP BY operation to allow us to consolidate repeated rows. In your question, you want to roll up all the same values except for the r_ticket_id. For that one, you wish to find the biggest value which in SQL translates to the MAX function.

SELECT
    name_text
,   c_num
,   d_type
,   unique_id
,   v_text
,   MAX(r_ticket_id) AS max_r_ticket_id
FROM
    dbo.MyTableNameHere
GROUP BY
    name_text
,   c_num
,   d_type
,   unique_id
,   v_text

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.