如何组合两个选择或两个查询?

时间:2013-08-20 13:41:36

标签: sql sql-server

我有两个问题。第一:

SELECT TOP 10   NewsItemTitle
            ,   COUNT(1) AS CounterNews
FROM [ACTIVITY]
WHERE [UserLocation] = 'United States'
GROUP BY NewsItemTitle
ORDER BY CounterNews DESC

给我回复:

NewsItemTitle                                                        CounterNews
Afinan plan para casas con cuota de $180.000 por mes                      5
The Exploratoreum's STEM seller                                           4
Witnesses at Hasan trial describe carnage of Ft. Hood shootings.          2
U.S. returns to FIFA top 20 after two-year absence                        2
Sunnyvale: Police shoot and kill man; body of woman found inside house    1
...

另外,我想在该查询中添加字段[NewsItemUrl][NewsItemPublisher]

SELECT  [NewsItemUrl]
    ,   [NewsItemPublisher]
FROM [ACTIVITY]

那么,我如何将这2个查询合并为1?

3 个答案:

答案 0 :(得分:3)

试试这个 -

SELECT TOP 10
      NewsItemTitle 
    , [NewsItemUrl] = MAX([NewsItemUrl])
    , [NewsItemPublisher] = MAX([NewsItemPublisher])
    , COUNT(1) AS CounterNews
FROM dbo.[ACTIVITY]
WHERE [UserLocation] = 'United States'
GROUP BY NewsItemTitle
ORDER BY CounterNews DESC

或者这个 -

SELECT TOP 10
      NewsItemTitle 
    , [NewsItemUrl]
    , [NewsItemPublisher]
    , COUNT(1) AS CounterNews
FROM dbo.[ACTIVITY]
WHERE [UserLocation] = 'United States'
GROUP BY 
       NewsItemTitle 
    , [NewsItemUrl]
    , [NewsItemPublisher]
ORDER BY CounterNews DESC

答案 1 :(得分:2)

如果我理解正确,您希望包含两列不属于GROUP BY的列。通常情况下不允许这样做,您必须将它们包含在组中或以其他方式聚合它们(例如MIN/MAX/COUNT)。

但你可以在common-table-expression中使用ranking function之类的ROW_NUMBER

WITH CTE AS
(
    SELECT NewsItemTitle, 
           NewsItemUrl, NewsItemPublisher,
           CounterNews = COUNT(*) OVER (PARTITION BY NewsItemTitle),
           RN = ROW_NUMBER() OVER (PARTITION BY NewsItemTitle ORDER BY CounterNews DESC)
    FROM [ACTIVITY] 
    WHERE [UserLocation] = 'United States' 
)
SELECT TOP 10 * 
FROM CTE 
WHERE RN = 1

正如您所看到的,OVER子句也适用于COUNT之类的聚合函数,它允许在不使用GROUP BY的情况下对每个组进行计数。

答案 2 :(得分:2)

我同意Devart的回答,但如果您不想按NewsItemUrl和NewsItemPublisher进行分组,这是您可以实现的另一种方式。

SELECT DISTINCT [NewsItemUrl]
     ,  [NewsItemPublisher]
    , TMP.NewsItemTitle
    , CounterNews
FROM [ACTIVITY] ACT
INNER JOIN 
(
SELECT TOP 10   NewsItemTitle
            ,   COUNT(1) AS CounterNews
FROM [ACTIVITY]
WHERE [UserLocation] = 'United States'
GROUP BY NewsItemTitle
ORDER BY CounterNews DESC
) TMP ON ACT.NewsItemTitle = TMP.NewsItemTitle