2017-10-11 181 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