考虑我们有一个带有此列的表 ID fk_newsId fk_NewsGroupId fk_NewsZoneId
我需要选择所有具有相同fk_NewsGroup和fk_NewsZone的记录 像这样
+----+-----------+--------------+-------------+
| Id | fk_NewsId | fk_NewsGroup | fk_NewsZone |
+----+-----------+--------------+-------------+
| 1 | 60 | 5 | 8 |
| 2 | 30 | 5 | 8 |
| 3 | 31 | 9 | 20 |
| 4 | 5 | 9 | 20 |
| 5 | 12 | 9 | 20 |
| 6 | 1000 | 20 | 11 |
| 7 | 21 | 20 | 11 |
| 8 | 6 | 20 | 11 |
+----+-----------+--------------+-------------+
该怎么做? 我像这样分组 但是它并没有给出期望的输出
select fk_NewsId, fk_NewsGroup,fk_NewsZone from tbl_test
group by fk_NewsGroup,fk_NewsZone,fk_NewsId
答案 0 :(得分:1)
您可以尝试将COUNT
与窗口功能一起使用,以通过count
和fk_NewsGroup
列获取fk_NewsZone
。
然后获得大于一的计数。
SELECT *
FROM (
SELECT *,COUNT(*) OVER(PARTITION BY fk_NewsGroup,fk_NewsZone ORDER BY fk_NewsZone) cnt
FROM tbl_test
)t1
where t1.cnt > 1
答案 1 :(得分:1)
关于您的意思不是很清楚,但是类似:
SELECT t.Id, t.fk_NewsId, t.fk_NewsGroup, t.fk_NewsZone FROM tbl_test t
INNER JOIN (
SELECT fk_NewsGroup,fk_NewsZone, COUNT(*) AS Counted FROM tbl_test
GROUP BY fk_NewsGroup,fk_NewsZone
HAVING COUNT(*) > 1) g
ON t.fk_NewsGroup = g.fk_NewsGroup
AND t.fk_NewsZone = g.fk_NewsZone
答案 2 :(得分:0)
我将使用Group by并执行以下操作:
select max(id) as Id, Max(fk_NewsId) as fk_NewsId, fk_NewsGroup,fk_NewsZone from #temp
group by fk_NewsGroup,fk_NewsZone