简体   繁体   中英

How can I write query where query with specific where condition?

I have one table with one primary key and three foreign keys. Here my table with data

Id      RegistrationId        GroupId      ItemId   Value    
2345     68038                677           672      679    
3562     68038                357           783      423    
8236     NULL                 268           578      914    
7327     NULL                 677           672      467    
8733     NULL                 357           783      234

I want to write query to get this result

Id      RegistrationId        GroupId      ItemId   Value
2345     68038                677           672      679
3562     68038                357           783      423    
8236     NULL                 268           578      914

As you can see I want all rows that have RegistrationId 68038 and I also want other default values for other GroupId and ItemId. How can I write SQL query to get result like above ? Thanks on your responds. How can I do this in MySQL ?

You have tagged multiple databases, assuming it to be a SQL Server.

Try this query, it will give you the desired output.

SELECT Id,RegistrationId ,GroupId,ItemId,Value FROM
(
  SELECT * ,
  ROW_NUMBER() OVER( PARTITION BY GroupId,ItemId   ORDER BY RegistrationId DESC) RN
  FROM [TABLE_NAME]
 ) T
WHERE T.RN=1
ORDER BY RegistrationId DESC

Example with sample data

;WITH MY AS 
(
  SELECT * FROM (VALUES
  (2345 ,  68038  ,  677 , 672 , 679 ),
  (3562 ,  68038  ,  357 , 783 , 423 ), 
  (8236 ,  NULL   ,  268 , 578 , 914 ),
  (7327 ,  NULL   ,  677 , 672 , 467 ),
  (8733 ,  NULL   ,  357 , 783 , 234 ) 
  ) T(Id,RegistrationId ,GroupId,ItemId,Value)
)

SELECT Id,RegistrationId ,GroupId,ItemId,Value FROM
(
  SELECT * ,    
  ROW_NUMBER() OVER( PARTITION BY GroupId,ItemId   ORDER BY RegistrationId DESC) RN
  FROM MY
 ) T
WHERE T.RN=1
ORDER BY RegistrationId DESC

Output:

+------+----------------+---------+--------+-------+
| Id   | RegistrationId | GroupId | ItemId | Value |
+------+----------------+---------+--------+-------+
| 3562 | 68038          | 357     | 783    | 423   |
+------+----------------+---------+--------+-------+
| 2345 | 68038          | 677     | 672    | 679   |
+------+----------------+---------+--------+-------+
| 8236 | NULL           | 268     | 578    | 914   |
+------+----------------+---------+--------+-------+

I tried something like that and it worked, but its bit a hardcoded way:

    SELECT *
    FROM   MY
    WHERE  RegistrationId IS NOT NULL
    AND    GroupId IN (677, 357)
    UNION ALL
    SELECT *
    FROM   xxtest_tolga
    WHERE  GroupId NOT IN (677, 357);

Hope it works for you.

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