我有一个表有一个主键和三个外键。 这里是我的数据表
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
我想编写查询来获得此结果
Id RegistrationId GroupId ItemId Value
2345 68038 677 672 679
3562 68038 357 783 423
8236 NULL 268 578 914
如您所见,我想要所有具有RegistrationId 68038的行,并且我还想要其他GroupId和ItemId的其他默认值。如何编写SQL查询以获得如上所示的结果?谢谢你的回应。我怎么能在MySQL中做到这一点?
答案 0 :(得分:1)
您已标记多个数据库,假设它是SQL Server。
尝试此查询,它会为您提供所需的输出。
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
示例数据示例
;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
<强>输出:强>
+------+----------------+---------+--------+-------+
| Id | RegistrationId | GroupId | ItemId | Value |
+------+----------------+---------+--------+-------+
| 3562 | 68038 | 357 | 783 | 423 |
+------+----------------+---------+--------+-------+
| 2345 | 68038 | 677 | 672 | 679 |
+------+----------------+---------+--------+-------+
| 8236 | NULL | 268 | 578 | 914 |
+------+----------------+---------+--------+-------+
答案 1 :(得分:0)
我尝试了类似的东西并且它有效,但它有点硬编码方式:
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);
希望它适合你。