4

Please help me create a select SQL statement with the results column name get from the column values in origin table (tablename is Device_Part):

enter image description here

User can input many DeviceCode which have many dynamic PartTypeName, the PartTypeName value is the PartInfo.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Hien Nguyen
  • 53
  • 1
  • 5
  • Maybe you're looking for dynamic MS SQL pivot : http://stackoverflow.com/questions/10404348/sql-server-dynamic-pivot-query – Pham X. Bach Nov 01 '16 at 09:22
  • Thanks you very much, i try it but it may hard to understand for me, and maybe it have constant value, when my values is dynamic – Hien Nguyen Nov 01 '16 at 09:43
  • If I write your code for you I'll charge you my normal hourly rate! But I'll help you for free. Have a go. Make some mistakes. Learn some stuff on the way. Then come back with what you tried, and tell us in what way it does not work. Remember to include error messages and sample data. – David Rushton Nov 01 '16 at 09:47
  • Thanks for your advice! I will try it ! – Hien Nguyen Nov 02 '16 at 01:07

2 Answers2

3

This may help:

CREATE Table Device (
DeviceCode NVARCHAR(100) NOT NULL,
PartTypeName NVARCHAR(100) NOT NULL,
PartInfo NVARCHAR(100) NOT NULL
)

Insert Into Device
Values('VT.SX-01','CPU','Pentium G6650'),
('VT.SX-01','Motherboard','H81M -  S2PV'),
('VT.SX-01','RAM','DDR# 4GB - bus 1866 - Nano'),
('VT.SX-01','PartType Name 01','PartInfo 01')

--QUERY
DECLARE @DynamicPivotQuery AS NVARCHAR(MAX);
DECLARE @ColumnNamesInPivot AS NVARCHAR(MAX);

--Get distinct values of PIVOT Column 
SELECT   @ColumnNamesInPivot = ISNULL(@ColumnNamesInPivot + ',', '')
        + QUOTENAME([PartTypeName])
FROM    ( SELECT    DISTINCT
                    [PartTypeName]
          FROM      Device
        ) AS P



SELECT  @DynamicPivotQuery = N'Select DeviceCode,'
        + @ColumnNamesInPivot + ' 
            FROM    ( SELECT * 
          FROM      Device
        ) AS SourceTable PIVOT( MAX(PartInfo) FOR [PartTypeName] IN ('
        + @ColumnNamesInPivot + ') ) AS PVTTable'

EXEC sp_executesql @DynamicPivotQuery;

And the result will be:

enter image description here

Yared
  • 2,206
  • 1
  • 21
  • 30
  • Thanks you very much for your work hard answer ! I run the first select success: https://farm6.staticflickr.com/5560/30407745360_5dc7583532_o_d.jpg , but the second is failed: https://farm6.staticflickr.com/5532/30707958185_4e3460c27e_o_d.jpg . Could you please help me try it, thanks you so much! – Hien Nguyen Nov 01 '16 at 10:13
  • and error if i run 2 select together: https://farm6.staticflickr.com/5343/30708083475_535c6c2196_o_d.jpg . Could you please help me try it, thanks you so much! – Hien Nguyen Nov 01 '16 at 10:22
  • 1
    I have edited the query... in order to get the desired out put, you need to select the query part from declaration of variables upto the end – Yared Nov 01 '16 at 10:24
  • Hien Nguyen, did you get what you wanted? – Yared Nov 01 '16 at 11:07
  • You are my master, the result is exactly my expected, thousand like for you, Thanks you very much for your enthusiastically help! https://farm6.staticflickr.com/5702/30090888554_d947cf4179_o_d.jpg . I would like to learn this technical SQL, could you please help me the technical name so i can find this on google. Thanks you! – Hien Nguyen Nov 02 '16 at 01:33
  • You are welcome! The following links may help you get the general idea about SQL PIVOT and dynamic sql queries: https://technet.microsoft.com/en-us/library/ms177410(v=sql.105).aspx,http://www.techrepublic.com/blog/the-enterprise-cloud/generate-dynamic-sql-statements-in-sql-server/, https://www.mssqltips.com/sqlservertip/1160/execute-dynamic-sql-commands-in-sql-server/, https://msdn.microsoft.com/en-us/library/ms188001.aspx – Yared Nov 02 '16 at 06:29
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/127147/discussion-between-yared-and-hien-nguyen). – Yared Nov 02 '16 at 06:30
1
Try this

;WITH _CTE(_DeviceCode,_PartTypeName,_PartInfo,_Id)
AS
(
 SELECT DeviceCode,PartTypeName,PartInfo ,ROW_NUMBER() OVER (PARTITION BY      PartTypeName ORDER BY Id) FROM Your_tablename
)
SELECT *
FROM
(
SELECT _DeviceCode,_PartTypeName,_PartInfo
FROM _CTE
)C
PIVOT
(
 MAX(_PartInfo) FOR _PartTypeName IN ([CPU],[MotherBoard],[RAM],[PartTypeName])
) AS PivotTable;
Chanukya
  • 5,833
  • 1
  • 22
  • 36
Mansoor
  • 4,061
  • 1
  • 17
  • 27
  • Thanks you very much for your answer, but the PartTypeName is dynamic, not only are [CPU],[MotherBoard],[RAM] , we can input more as Power, Monitor, Keyboard...... – Hien Nguyen Nov 01 '16 at 09:45