SQL Server- Merge rows into one column and take maximum count

Ask_SO

I am working on a query that will collect data from joining multiple tables and display the data.

The data looks like this:

Region                  CountryName  ProductID
Latin America/Caribbean BAHAMAS         21
Europe                  AZERBAIJAN      23
Europe                  AZERBAIJAN      24
Latin America/Caribbean BAHAMAS         21
Middle East/Africa      BAHRAIN         43
Europe                  BALI            21
Asia Pacific            BANGLADHESH     25
Asia Pacific            BANGLADHESH     256
Latin America/Caribbean BARBADOS        20      
Europe                  BELARUS         15
Europe                  BELGIUM         24

And I want the result set like this

Region                  CountryName                         ProductID       RecordCount
Latin America/Caribbean BAHAMAS,BARBADOS                    21,20           2
Europe                  AZERBAIJAN,BALI,BELARUS,BELGIUM     23,15,24        4
Asia Pacific            BANGLADHESH                         25,26           2
Middle East/Africa      BAHRAIN                             43              1

I have tried below Query to merge CountryName and ProductID but I want the 4th Column count value which ever is maximum b/w Product&Country columns. (i.e., If CountryName column has 4 Countries and Product column has 2 then my count should be 4 (2nd Row in the above resultset) and If Product column has two Id and country has single country name then my Count should be 2(3rd row in the above resulset) and it should be grouped by Region.

SELECT RegionName,
STUFF((SELECT DISTINCT ', ' + CAST(COUNTRY AS NVARCHAR(20)) FROM Countries RX WHERE RX.CountryCode = PD.CountryCode FOR XML PATH('')),1,1,'') AS CountryList,
STUFF((SELECT DISTINCT ', ' + CAST(ProductID AS NVARCHAR(5)) FROM Product RP WHERE RP.ProductID = PD.ProductID FOR XML PATH('')),1,1,'') AS ProductList,
Count(?) AS recCount
FROM Countries CN WITH (NOLOCK)
INNER JOIN Product PD WITH (NOLOCK)
ON PD.CountryCode=CN.CountryCode 
GROUP BY RegionName

Does anyone have an idea on how to make this?

Suraj Kumar

You can try the following query using stuff(), len() functions and inner join.

create table #Region (Region  Varchar(50), CountryName Varchar(50),  ProductID int)
insert into #Region values
('Latin America/Caribbean', 'BAHAMAS', 21),
('Europe', 'AZERBAIJAN', 23),
('Europe', 'AZERBAIJAN', 24),
('Latin America/Caribbean', 'BAHAMAS', 21),
('Middle East/Africa', 'BAHRAIN', 43),
('Europe', 'BALI', 21),
('Asia Pacific', 'BANGLADHESH', 25),
('Asia Pacific', 'BANGLADHESH', 256),
('Latin America/Caribbean', 'BARBADOS', 20),    
('Europe', 'BELARUS', 15),
('Europe', 'BELGIUM', 24)

Now the actual query is as shown below:

Select a.Region, a.CountryName, b.ProductID, 
Case when LEN(b.ProductID) - LEN(REPLACE(b.ProductID, ',',''))+1 
> 
LEN(a.CountryName) - LEN(REPLACE(a.CountryName, ',',''))+1
then 
    LEN(b.ProductID) - LEN(REPLACE(b.ProductID, ',',''))+1
else
    LEN(a.CountryName) - LEN(REPLACE(a.CountryName, ',',''))+1
end as RecordCount
 from(
Select
    g1.Region
    , stuff((
        select distinct ', ' + g.CountryName
        from #Region g        
        where g.Region = g1.Region 
        for xml path('')
    ),1,2,'') as CountryName    
from #Region g1
group by g1.Region
)a inner join
(
Select
    g1.Region
    , stuff((
        select distinct ', ' + Cast(g.ProductID as CHAR(3))
        from #Region g        
        where g.Region = g1.Region 
        for xml path('')
    ),1,2,'') as ProductID    
from #Region g1
group by g1.Region
)b on a.Region = b.Region

The output is as shown below.

Region                  CountryName                      ProductID     RecordCount
-----------------------------------------------------------------------------------
Asia Pacific              BANGLADHESH                        25 , 256             2
Europe                    AZERBAIJAN, BALI, BELARUS, BELGIUM 15 , 21 , 23 , 24    4
Latin America/Caribbean   BAHAMAS, BARBADOS                  20 , 21              2
Middle East/Africa        BAHRAIN                            43                   1

You can find the live demo Here.

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

Merge data into one column - sql server 2012

分類Dev

Finding the maximum sum of a column for any 3 rows in SQL Server

分類Dev

Merge multiple rows into one row using SQL Server?

分類Dev

How to combine multiple rows into one row and multiple column in SQL Server?

分類Dev

Merge multiple columns into one column with multiple rows

分類Dev

SQL query to determine the column based on count of rows

分類Dev

How to select all rows that share a maximum value in a column using SQL

分類Dev

Total Count of column value in Sql Server

分類Dev

Get DISTINCT COUNT in one pass in SQL Server

分類Dev

SQL server how to convert column values into rows

分類Dev

convert rows to column using sql server

分類Dev

Combine Multiple Rows into One Row (One Column) when Using SQL

分類Dev

SQL query to count rows based on previous values of different column

分類Dev

SQL Server - Rows to column based on third column value

分類Dev

Merge ranges in one column

分類Dev

SQL Server - Merge multiple query results into one result set

分類Dev

Maximum count of stored procedure in SQL

分類Dev

Count number of IDs in one column matching multiple defined IDs (rows) in another column

分類Dev

Multiple rows to one column

分類Dev

How do I count in SQL Server occurences in put in another column?

分類Dev

How to get COUNT(*) from one partition of a table in SQL Server 2012?

分類Dev

Get number of rows per length on a column in SQL Server

分類Dev

SQL Server: Select rows with multiple occurrences of regex match in a column

分類Dev

Pivoting rows to columns with custom column names in SQL Server

分類Dev

SQL Server: Combine multiple rows into one with no overlap but new columns

分類Dev

Merging rows to one row with inner join in SQL Server

分類Dev

SQL: count rows where column = a value AND another column is the same as values in the group where the first condition is true?

分類Dev

SQL Server MERGE Slow

分類Dev

SQL Server MERGE Slow

Related 関連記事

  1. 1

    Merge data into one column - sql server 2012

  2. 2

    Finding the maximum sum of a column for any 3 rows in SQL Server

  3. 3

    Merge multiple rows into one row using SQL Server?

  4. 4

    How to combine multiple rows into one row and multiple column in SQL Server?

  5. 5

    Merge multiple columns into one column with multiple rows

  6. 6

    SQL query to determine the column based on count of rows

  7. 7

    How to select all rows that share a maximum value in a column using SQL

  8. 8

    Total Count of column value in Sql Server

  9. 9

    Get DISTINCT COUNT in one pass in SQL Server

  10. 10

    SQL server how to convert column values into rows

  11. 11

    convert rows to column using sql server

  12. 12

    Combine Multiple Rows into One Row (One Column) when Using SQL

  13. 13

    SQL query to count rows based on previous values of different column

  14. 14

    SQL Server - Rows to column based on third column value

  15. 15

    Merge ranges in one column

  16. 16

    SQL Server - Merge multiple query results into one result set

  17. 17

    Maximum count of stored procedure in SQL

  18. 18

    Count number of IDs in one column matching multiple defined IDs (rows) in another column

  19. 19

    Multiple rows to one column

  20. 20

    How do I count in SQL Server occurences in put in another column?

  21. 21

    How to get COUNT(*) from one partition of a table in SQL Server 2012?

  22. 22

    Get number of rows per length on a column in SQL Server

  23. 23

    SQL Server: Select rows with multiple occurrences of regex match in a column

  24. 24

    Pivoting rows to columns with custom column names in SQL Server

  25. 25

    SQL Server: Combine multiple rows into one with no overlap but new columns

  26. 26

    Merging rows to one row with inner join in SQL Server

  27. 27

    SQL: count rows where column = a value AND another column is the same as values in the group where the first condition is true?

  28. 28

    SQL Server MERGE Slow

  29. 29

    SQL Server MERGE Slow

ホットタグ

アーカイブ