作者:coffee_陈--嘉辉 | 来源:互联网 | 2023-05-19 07:36
Ihaveonetablewithoneprimarykeyandthreeforeignkeys.Heremytablewithdata我有一个表有一个主键和三个外
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 ?
如您所见,我想要所有具有RegistrationId 68038的行,并且我还想要其他GroupId和ItemId的其他默认值。如何编写SQL查询以获得如上所示的结果?谢谢你的回应。我怎么能在MySQL中这样做?
2 个解决方案
1
You have tagged multiple databases, assuming it to be a SQL Server.
您已标记多个数据库,假设它是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 |
+------+----------------+---------+--------+-------+