合并查询与组

时间:2016-05-24 02:18:32

标签: sql sql-server

你好我使用SQL Server我想按分类合并数据 我有这样的查询

SELECT a.NamaMerk, b.NamaTipe from MsMerk as a inner join MsTipe  as b 
on a.ID_Merk = b.ID_Merk where a.FlagActive='Y' and b.FlagActive='Y' and a.ID_Merk = b.ID_Merk and b.ID_Tipe = b.ID_Tipe

此显示数据

enter image description here

我希望数据显示如下

  

三星:Galaxy S7

         Galaxy S8 
  

华硕:Zenfone 4

         Zenfone 5

就像按类别合并数据一样,请帮助我谢谢

2 个答案:

答案 0 :(得分:2)

试一试。我使用row_number按NamaMerk排名,然后当它大于1时我将其设置为空字符串

    SELECT CASE 
         WHEN T.rank > 1 THEN '' 
         ELSE T.NamaMerk 
       END        AS 'NamaMerk', 
       T.NamaTipe AS 'NamaTipe' 
FROM   (SELECT a.NamaMerk, 
               b.NamaTipe, 
               Row_number() 
                 OVER( 
                   partition BY a.NamaMerk 
                   ORDER BY b.NamaTipe) AS 'RANK' 
        FROM   msmerk AS a 
               INNER JOIN mstipe AS b 
                       ON a.id_merk = b.id_merk 
        WHERE  a.flagactive = 'Y' 
               AND b.flagactive = 'Y' 
               AND a.id_merk = b.id_merk ) T

答案 1 :(得分:2)

DECLARE @tab TABLE (NamaMerk VARCHAR(10), NamaTipe VARCHAR(10))
INSERT INTO @tab
VALUES ('Samsung','Galaxy S7'),('Samsung','Galaxy S6'),
('Apple','iPhone 5'),('LG','G5'),('Asus','Zenfone 4'),
('Asus','Zenfone 7'),('Xiami', 'Mi Note 3'),
('Asus','Zenfone 5')

;WITH cte AS 
(
 SELECT *,ROW_NUMBER() OVER(PARTITION BY NamaMerk ORDER BY NamaTipe) AS Rn
 FROM @tab
)
SELECT CASE WHEN Rn=1 THEN NamaMerk + ':' + NamaTipe 
  ELSE REPLICATE(' ',LEN(NamaTipe)) + NamaTipe END AS Result
FROM cte;

使用Row_Number,当它为1时,连接NamaMerk和NamTipe其他空间加上NamaTipe。

我认为您可能必须在SSRS中执行此操作,因为它与显示有关。