Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I need the a report of all masterid's but it may only be one on a row.. I know that's a simple thing to do but I can't figure out the syntax correctly.

I attached the data how its stored in SQL server and the output how I want it to be.

Data:

data

Required Output:

Required Output

CREATE TABLE [dbo].[Services]
    ([ServiceID] [int] IDENTITY(1,1) NOT NULL,
    [MasterID] [nvarchar](10) NOT NULL,
    [Type] [nvarchar](50) NOT NULL,
    [Status] [nvarchar](50) NOT NULL)

Insert Into Services (MasterID, Type , Status) values (123, 'Basic Phone', 'Open')
Insert Into Services (MasterID, Type , Status) values (123, 'BlackBerry', 'Open')
Insert Into Services (MasterID, Type , Status) values (123, 'Pixi', 'Closed')
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.3k views
Welcome To Ask or Share your Answers For Others

1 Answer

SELECT MasterID, 
  [Basic Phone] = MAX([Basic Phone]),
  [Pixi] = MAX([Pixi]),
  [Blackberry] = MAX([Blackberry])
FROM
(
  SELECT MasterID, [Basic Phone],[Pixi],[Blackberry]
  FROM dbo.Services AS s
  PIVOT 
  (
    MAX([Status]) FOR [Type] IN ([Basic Phone],[Blackberry],[Pixi])
  ) AS p
) AS x
GROUP BY MasterID;

Or more simply - and credit to @YS. for pointing out my redundancy.

SELECT MasterID, 
  [Basic Phone],
  [Pixi],
  [Blackberry]
FROM
(
  SELECT MasterID, Status, Type FROM dbo.Services
)
AS s
PIVOT 
(
  MAX([Status]) FOR [Type] IN ([Basic Phone], [Blackberry], [Pixi])
) AS p;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...