Have a problem find a query for my tables
I have 2 tables table A and table B as follow
table A
---------------------
| Name | addrid |
---------------------
| zlai | 1 |
| blai | 2 |
table B
---------------------
| addrid | addr |
---------------------
| 1 | AMERICA |
| 1 | SPAIN |
| 1 | MEXICO |
| 2 | TURKEY |
The result I need is
--------------------------
| Num | Name | addr |
--------------------------
| 1 | zlai | AMERICA |
| | | SPAIN |
| | | MEXICO |
| 2 | blai | TURKEY |
Query I have tried so far
http://sqlfiddle.com/#!12/3ac39/12
You can concatenate rows into single string using COALESCE method. This COALESCE method can be used in SQL Server version 2008 and higher. All you have to do is, declare a varchar variable and inside the coalesce, concat the variable with comma and the column, then assign the COALESCE to the variable.
The SQL GROUP BY Statement The GROUP BY statement groups rows that have the same values into summary rows, like "find the number of customers in each country". The GROUP BY statement is often used with aggregate functions ( COUNT() , MAX() , MIN() , SUM() , AVG() ) to group the result-set by one or more columns.
The SQL GROUP BY clause is used along with some aggregate functions to group columns that have the same values in different rows. The group by multiple columns technique is used to retrieve grouped column values from one or more tables of the database by considering more than one column as grouping criteria.
SELECT CASE WHEN No != 1
THEN ''
ELSE CAST(a.addrid AS VARCHAR(20))
END AS Num,
CASE WHEN No != 1
THEN ''
ELSE name
END AS name,
addr
FROM
(
SELECT ROW_NUMBER() OVER (PARTITION BY a.addrid
ORDER BY name DESC) AS No,
name,
addr,
a.addrid
FROM a LEFT JOIN b ON a.addrid = b.addrid
) a
ORDER BY a.addrid
I try to modified the addrid
values by 101 and 325 (for example)
table A
---------------------
| Name | addrid |
---------------------
| zlai | 101 |
| blai | 325 |
table B
---------------------
| addrid | addr |
---------------------
| 101 | AMERICA |
| 101 | SPAIN |
| 101 | MEXICO |
| 325 | TURKEY |
the query is:
SELECT CASE WHEN No != 1
THEN ''
ELSE CAST(row AS VARCHAR(20))
END AS Num,
CASE WHEN No != 1
THEN ''
ELSE name
END AS name,
addr
FROM
(
SELECT ROW_NUMBER() OVER (PARTITION BY a.addrid
ORDER BY name DESC) AS No,
name,
addr,
DENSE_RANK() OVER (ORDER BY a.addrid) "row"
FROM a LEFT JOIN b ON a.addrid = b.addrid
) a
ORDER BY row
and the result is same as you want.
SQL Fiddle Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With