当我们使用group by时是否可以访问组中的行

时间:2019-01-08 08:42:01

标签: sql

我有一个如下表,其中可以复制country

CustomerID  CustomerName                        ContactName     Address City PostalCode Country
1           Alfreds Futterkiste                 Maria Anders    Obere Str. 57   Berlin  12209   Germany
2           Ana Trujillo Emparedados y helados  Ana Trujillo    Avda. de la Constitución 2222   México D.F. 05021   Mexico
3           Antonio Moreno Taquería             Antonio Moreno  Mataderos 2312  México D.F. 05023   Mexico
...

我创建了一个查询,该查询将告诉我每个国家/地区的计数(例如4条记录,德国,2条墨西哥,等等)。

select Country, count(Country) AS Count 
from (
  SELECT * 
  FROM Customers 
  order by Country
) 
group by Country

我知道

Country City    count
Argentina       3
Austria         2

我想GROUP BY子句中列出的列用于形成组。分组基于指定列中具有相同值的行或放置在同一组中的列。因此,在上面的示例中,Argentina组包含3行。是否可以访问组中的各个行,以便我也可以输出结果中的城市?

类似

Country     City                  count
Argentina   city1, city2, city3   3
Austria     city1, city2          2

3 个答案:

答案 0 :(得分:0)

您可以将分组表加入原始表:

select cu.*, co.cnt from Customers cu
join  (
    select Country, count(Country) cnt AS Count
    from Customers
    group by Country
) co on cu.Country = co.Country

这是标准的SQL,应可在任意RDBMS上运行(至少在大多数RDBMS上均可)。

根据RDBMS,您可以使用一些特定的方法,例如字符串聚合或窗口函数(SSMS)。

答案 1 :(得分:0)

您可以尝试下面的代码。

ALTER PROC dbo.GEN_SP_G_CONCATDATAs 如 开始 声明@CountryName AS INT,@RowCtry AS INT = 1,@Cities AS VARCHAR(max)='',@RowCity AS INT = 1 宣告@tmpTableCountry TABLE(ID INT,Country VARCHAR(max)) 插入@tmpTableCountry     (ID,国家) SELECT ROW_NUMBER()OVER(ORDER BY ISNULL(Country,0)ASC),-ID-int     ISNULL(国家,0)-国家-varchar(最大值) 来自dbo.tmpCustomerTable 按国家分组 @RowCtry <=时(从@tmpTableCountry中选择MAX(ID)) 开始     从@tmpTableCountry中选择@CountryName = ISNULL(Country,'')WHERE ID = @RowCtry

if object_id('tempdb.dbo.#tmpTableCity') is not null
drop table #tmpTableCity
CREATE TABLE #tmpTableCity(ID INT,City VARCHAR(max))

INSERT INTO #tmpTableCity
        ( ID, City )
SELECT  ROW_NUMBER() OVER(ORDER BY CustomerID ASC) , -- ID - int
        City  -- Country - varchar(max)
FROM dbo.tmpCustomerTable
WHERE Country = @CountryName 

SET @Cities = ''
SET @RowCity = 1    

DECLARE @cnt AS INT = 0

SELECT @cnt = COUNT(*) FROM #tmpTableCity

WHILE @RowCity <= @cnt
    BEGIN
        SET @Cities = @Cities + (SELECT ISNULL(City,'') FROM #tmpTableCity WHERE ID = @RowCity) + ','
        SET @RowCity = @RowCity + 1
    END

DECLARE @tmpTableResult TABLE(Country VARCHAR(max),City VARCHAR(max),Cnt INT)

INSERT INTO @tmpTableResult
        ( Country, City, Cnt )
VALUES  ( @CountryName, -- Country - varchar(max)
          @Cities, -- City - varchar(max)
          @cnt  -- Cnt - int
          )

SET @RowCtry = @RowCtry + 1

END

选择*来自@tmpTableResult 结束 开始

答案 2 :(得分:-1)

select country, city, count(*) as count
from customers
group by country, city
order by country, city

SELECT country, 
LISTAGG(city, ', ') WITHIN GROUP (ORDER BY city) as cities,
count (*) as count 
FROM customers
GROUP BY country 
ORDER BY country