Use Value of a Column into another Column Name [closed] - sql

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Here are the values:
id | cat | AttribGroup | AttribID | Value
1 1 test 001 beautiful
1 1 test 002 handsome
Now what I what I want to happen is:
id | cat | test_001 | test_002
1 1 beautiful handsome

You may check this fiddle
It consists of a PIVOT and then join the results to the initial table.
Since i guess that your values are not going to be just test_001 and test_002 you are going to need some dynamic SQL in order to define the columns.
The code :
DECLARE #cols AS VARCHAR(MAX),
#query AS VARCHAR(MAX)
SET #cols = STUFF((SELECT distinct ',[' + AttribGroup + '_' + AttribID +']'
FROM Table1 c
FOR XML PATH(''), TYPE
).value('.', 'VARCHAR(MAX)')
,1,1,'')
SET #query =
';WITH MyCTE AS
(
SELECT *
FROM
(
SELECT AttribGroup + ''_'' + AttribID AS ColName,
CONVERT(VARCHAR,id)+''_''+CONVERT(VARCHAR,cat) AS idcat,
Value
FROM Table1
) p
PIVOT
(
MAX (Value)
FOR ColName IN (' + #cols + ')
) AS pvt
)
SELECT t.id,
t.cat,
m.*
FROM MyCTE m
JOIN
(
SELECT id,
cat,
CONVERT(VARCHAR,id)+''_''+CONVERT(VARCHAR,cat) as idcat
FROM Table1
GROUP BY id,
cat
) t
ON m.idcat = t.idcat'
EXEC(#query)

Related

How to swap table values to column in sql [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
TABLE A
P Q R
1 A a
2 B a
3 C b
4 D b
How can I convert it to
Table B
P a b
1 A -
2 B -
3 - C
4 - D
Hint: a is mapped with A&B not with C&D in table A. Similarly b is mapped with C&D not with A&B. Pivot is not working. Please help.
This could be achieved using a Dynamic CrossTab. For reference: http://www.sqlservercentral.com/articles/Crosstab/65048/
SAMPLE DATA
CREATE TABLE SampleData(
P INT,
Q CHAR(1),
R CHAR(1)
)
INSERT INTO SampleData
SELECT 1, 'A', 'a' UNION ALL
SELECT 2, 'B', 'a' UNION ALL
SELECT 3, 'C', 'b' UNION ALL
SELECT 4, 'D', 'b'
Dynamic Crosstab
DECLARE #sql1 VARCHAR(4000) = '',
#sql2 VARCHAR(4000) = '',
#sql3 VARCHAR(4000) = ''
SELECT #sql1 =
'SELECT
P' + CHAR(10)
SELECT #sql2 = #sql2 +
' ,MAX(CASE WHEN R = ''' + R + ''' THEN Q END) AS [' + R + ']' + CHAR(10)
FROM(
SELECT DISTINCT R FROM SampleData
)t
ORDER BY R
SELECT #sql3 =
'FROM SampleData
GROUP BY P
ORDER BY P
'
PRINT(#sql1 + #sql2 + #sql3)
EXEC(#sql1 + #sql2 + #sql3)
RESULT
P a b
----------- ---- ----
1 A NULL
2 B NULL
3 NULL C
4 NULL D
Try this
select P,
case when R='a' then a else '-' end as a,
case when R='b' then '-' else a end as b
from table_A

Convert couple of rows into single row based on Duplicate ID in sql server from single/same table

I am going to do some arthimetic calulation for particular Id with two different category code.
So i have the below two row as input,
I am expecting the below output as,
I am trying to do some self join but i am not luckly getting the desired output.
Can you pls help me out here?
Note: Only two row will come for particular ID (Two type of categories will come [A or C]).
Only two row will come for particular ID (Two type of categories will
come [A or C]).
Then this query should be sufficient:
SELECT ID,
ValueA = SUM(CASE WHEN Category = 'A' THEN Value END),
ValueC = SUM(CASE WHEN Category = 'C' THEN Value END)
FROM dbo.TableName
GROUP BY ID
Sql-Fiddle
Method 1:
Try this
SELECT *
FROM Table1
Pivot (MAX(value) for Category in ([A],[C])) as Value
Fiddle Demo
Output:
+-------------+-------+-------+
| ID | A |C |
+-------------+-------+-------+
| WD559606479 | 0.748 |2.088 |
+-------------+-------+-------+
Method 2: Dynamic Pivot
If you have one more column in the input then
Try this
DECLARE #cols AS NVARCHAR(MAX)
DECLARE #query AS NVARCHAR(MAX)
SET #cols = STUFF((SELECT distinct ',' + QUOTENAME(c.category)
FROM table1 c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
SET #query ='SELECT id, ' + #cols + ' from
(
SELECT id
, category
, value
FROM table1
) x
Pivot
(
Max(value)
For category In (' + #cols + ')
) P'
Execute(#query)
Fiddle Demo
Output:
+-------------+-------+-------+
| ID | A |C |
+-------------+-------+-------+
| WD559606479 | 0.748 |2.088 |
+-------------+-------+-------+

I am stuck in a situation while creating SQL for following scenario [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have tried using Case-End but nothing worked.
Diff types of phone number are :
Home
Cell
Main
OTPR
Busn
select emplid,
max(case when phone_type='home' then phone_number else -1 end) Home,
max(case when phone_type='cell' then phone_number else -1 end) Cell,
.....
from phone_data
group by emplid;
You can't mix character and numeric in one field, if you require n/a in the output you need another step which makes the phone number columns characters.
select t.empid as empid, cell.phone_number as cell, home.phone_number as Home
from telephones t
inner join telephones cell on t.empid = cell.empid
inner join telephones home on t.empid = home.empid
where cell.Phone_type = "cell"
and home.Phone_type = "home"
group by t.empid
and a sql fiddle : http://sqlfiddle.com/#!2/6bb17/11
Try this SQL query!
DECLARE #cols AS NVARCHAR(MAX),#query AS NVARCHAR(MAX);
SET #cols = STUFF((SELECT distinct ',' + QUOTENAME(c.phone_type)
FROM youtablename c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT empid, ' + #cols + ' from
(
select empid
, phone_number
, phone_type
from youtablename
) x
pivot
(
max(phone_number)
for phone_type in (' + #cols + ')
) p '
execute(#query)

SQL rotate rows to columns...dynamic number of rows [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
SQL Server dynamic PIVOT query?
I have a dataset that has the below structure.
CREATE TABLE #TempTable
(
Measure_ID INT,
measurement DECIMAL(18, 4)
)
INSERT INTO #TempTable
VALUES
(1,2.3)
,(1,3.4)
,(1,3.3)
,(2,3)
,(2,2.3)
,(2,4.0)
,(2,4.5)
I need to produce output that will look like this.
1,2.3,3.4,3.3
2,3,2.3,4.0,4.5
Basically its a pivot on Measure_ID. Unfortunately, there can be an unlimited number of measure_id's. So Pivot is out.
I'm hoping to avoid CURSORS, but will if that turns out to be the best approach.
If you have an unknown number of values, then you can use a PIVOT with dynamic SQL:
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
select #cols = STUFF((SELECT distinct ','
+ QUOTENAME('Measurement_' + cast(rn as varchar(10)))
from temptable
cross apply
(
select row_number() over(partition by measure_id order by measurement) rn
from temptable
) x
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT measure_id, ' + #cols + ' from
(
select measure_id, measurement,
''Measurement_''
+ cast(row_number() over(partition by measure_id order by measurement) as varchar(10)) val
from temptable
) x
pivot
(
max(measurement)
for val in (' + #cols + ')
) p '
execute(#query)
See SQL Fiddle With Demo
If you have a known number of values, then you can hard-code the values, similar to this:
SELECT measure_id, [Measurement_1], [Measurement_2],
[Measurement_3], [Measurement_4]
from
(
select measure_id, measurement,
'Measurement_'
+ cast(row_number() over(partition by measure_id order by measurement) as varchar(10)) val
from temptable
) x
pivot
(
max(measurement)
for val in ([Measurement_1], [Measurement_2],
[Measurement_3], [Measurement_4])
) p
See SQL Fiddle With Demo
Both queries will produce the same results:
MEASURE_ID | MEASUREMENT_1 | MEASUREMENT_2 | MEASUREMENT_3 | MEASUREMENT_4
==========================================================================
1 | 2.3 | 3.3 | 3.4 | (null)
2 | 2.3 | 3 | 4 | 4.5

display rows as column

I want to display rows as column in SQL Server.
My table looks like this:
images_id item_id images_name
-------------------------------
1 1 image1.jpg
2 1 image2.jpg
3 1 image3.jpg
4 2 image4.jpg
5 2 image5.jpg
6 2 image6.jpg
I'd like this output:
images_id item_id image1 image2 image3
------------------------------------------------------
1 1 image1.jpg image2.jpg image3.jpg
2 2 image4.jpg image5.jpg image6.jpg
Here is an image link.
Is this possible or not? item_id must be dynamically changeable (it is not stable).
Cross Tabs and Pivots, Part 1 – Converting Rows to Columns
Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs
Pivot table for Microsoft SQL Server
This isn't possible without using dynamic SQL. PIVOT requires you to specify the columns still.
Let me know if dynamic SQL is acceptable and I'll spin you an example.
Here is how you can use Dynamic SQL for this:
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
SET #cols = STUFF((SELECT distinct ',' + QUOTENAME('image' + cast(row_number() over(partition by itemid order by imageid) as varchar(5)))
FROM test c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT itemid, ' + #cols + ' from
(
select itemid, imagename,
''image'' + cast(row_number() over(partition by itemid order by imageid) as varchar(5)) col
from test
) x
pivot
(
min(imagename)
for col in (' + #cols + ')
) p '
execute(#query)
See SQL Fiddle with Demo