2017-10-11 107 views
-1
ALTER PROCEDURE [dbo].[spGetItemCategories] 
AS 
BEGIN 
    SET NOCOUNT ON; 
    --SELECT * FROM ItemCategories 

    SELECT 
     IC.Id, IC.Name ,C.Id AS CompanyId, C.Name AS CompanName 
    FROM 
     ItemCategories IC 
    JOIN 
     CompanyItems CI ON IC.Id = CI.ItemCategoryId 
    JOIN 
     Companies C ON CI.CompanyId = C.Id 
    --WHERE CI.CompanyId IN (SELECT TOP(100)* FROM Companies C) 
END 

这显示数据,如合并列表:如何从SQL Server存储过程

4 sdfs 14 Nestle 
4 sdfs 15 Unilever 

,但我想是这样的:

4 sdfs 14 Nestle 
      15 Unilever 

check image for code

+0

或此等值的EntityFramework –

+1

你混淆的领域数据无线显示器呈现。您在SSMS的结果选项卡中看到的呈现不是最终用户应该看到的内容(除非您计划对应用程序进行建模以使其看起来像SSMS)。强制数据库执行通常为应用程序保留的作业,一旦你接触到应用程序只会导致悲伤。 –

回答

-1

您可以检查这个方法只是相同的数据。

declare @mytable table (compid int,compname varchar(20),itemid int, itemdesc varchar(20)) 

insert into @mytable 
values 
(1,'Company A',100,'Nestle'), 
(1,'Company A',200,'UniLever'), 
(2,'Company B',300,'Citrix'), 
(2,'Company B',400,'SQL'), 
(2,'Company B',500,'Oracle'), 
(1,'Company B',600,'Microsoft') 


select 
iif(left(m1.ord_id,1)>1,NULL,m.compid) [CompID], 
iif(left(m1.ord_id,1)>1,NULL,m.compname) [CompName], 
m.itemid, 
m.itemdesc 
from @mytable m 
inner join (
    select distinct compid,row_number() over (partition by compid order by itemid) [ord_id], itemid 
    from @mytable) m1 
    on m.compid = m1.compid and m.itemid = m1.itemid 

或CTE

;with cte as 
(
select distinct compid,row_number() over (partition by compid order by itemid) [ord_id], itemid 
from @mytable 
) 
select 
iif(left(m1.ord_id,1)>1,NULL,m.compid) [CompID], 
iif(left(m1.ord_id,1)>1,NULL,m.compname) [CompName], 
m.itemid, 
m.itemdesc 
from @mytable m 
inner join cte m1 
on m.compid = m1.compid and m.itemid = m1.itemid 

,如果你不快乐与空值替换

iif(left(m1.ord_id,1)>1,'',cast(m.compid as varchar)) [CompID], 
iif(left(m1.ord_id,1)>1,'',m.compname) [CompName], 

结果

CompID CompName itemid itemdesc 
1  Company A 100  Nestle 
        200  UniLever 
        600  Microsoft 
2  Company B 300  Citrix 
        400  SQL 
        500  Oracle 
+0

你仅仅通过很多步骤进行简单的演示。从数据库的角度来看,OP的SQL是正确的。我会说他们需要认识到演示和数据之间的区别。 NULL不是IMO的解决方案。你不同意吗? – smoore4

+0

你为什么不创建你的解决方案@ smoore4,让我成为法官。怎么样? – maSTAShuFu

+0

NULL只是SQL的一个结果,你可以随时重新格式化它......这只是一个概念,有一个解决方案。 – maSTAShuFu