How to PIVOT this data in SQL Server? - sql-server

I have this query below
select * from (
SELECT tjdm.ID as id, cjb.CORPORATE_ID,
tjdm.JOB_TICKET_VALUE, cjb.DISPLAY_NAME
from Cjd cjb
join Tjdm tjdm
on cjb.CUSTOM_JOB_DATA_ID = tjdm.CUSTOM_JOB_DATA_ID
where cjb.CUSTOM_DATA_TYPE in (1,2) and cjb.DISPLAY_IS_ACTIVE = 1
) AS PivotData
PIVOT (
max(JOB_TICKET_VALUE)
FOR DISPLAY_NAME IN
([OMXAccount],[Consignee],[Col1],[Col2],[Col3],[Col4])
) AS PivotTable
The select * from (.....) returns a data columns as shown below.
id CORPORATE_ID JOB_TICKET_VALUE DISPLAY_NAME
-- ------------ ---------------- ------------
53 1 9 OMXAccount
53 1 199 Consignee
54 6 "No value" OMXAccount
54 6 "No value" Consignee
58 1 "No value" OMXAccount
58 1 "No value" Consignee
But when the "PIVOT" statement being executed, I am getting this result.
id CORPORATE_ID OMXAccount Consignee [Col1] [Col2] [Col3] [Col4]
-- ------------ ---------- --------- ------ ------ ------ ------
53 1 9 199 Null Null Null Null
54 6 Null Null Null Null
58 1 Null Null Null Null
The expected output should be just like below.
id CORPORATE_ID OMXAccount Consignee [Col1] [Col2] [Col3] [Col4]
-- ------------ ---------- --------- ------ ------ ------ ------
53 1 OMXAccount Consignee Null Null Null Null
54 6 OMXAccount Consignee Null Null Null Null
58 1 OMXAccount Consignee Null Null Null Null
What is wrong?
Thanks
RJuy

select * from (
SELECT tjdm.ID as id, cjb.CORPORATE_ID,
cjb.DISPLAY_NAME
from Cjd cjb
join Tjdm tjdm
on cjb.CUSTOM_JOB_DATA_ID = tjdm.CUSTOM_JOB_DATA_ID
where cjb.CUSTOM_DATA_TYPE in (1,2) and cjb.DISPLAY_IS_ACTIVE = 1
) AS PivotData
PIVOT (
max(DISPLAY_NAME)
FOR DISPLAY_NAME IN
([OMXAccount],[Consignee],[Col1],[Col2],[Col3],[Col4])
) AS PivotTable

Related

How to get only a distinct row

I have a table which is shown on below
id locale roaming rent
301 NULL 18.00 NULL
300 NULL NULL 5.00
299 11.00 NULL NULL
298 NULL NULL 4.00
297 NULL 20.00 NULL
296 NULL NULL 6.00
295 9.00 NULL NULL
294 NULL 20.00 NULL
293 10.00 NULL NULL
I want to get only one value in each column (without id column) in a row. How can I do it? BUT I want to do it only in one select query.
A possible solution:
SELECT (
SELECT TOP 1 [local]
FROM tbl
WHERE [local] IS NOT NULL
ORDER BY [id] DESC
) AS [local]
,(
SELECT TOP 1 [roaming]
FROM tbl
WHERE [roaming] IS NOT NULL
ORDER BY [id] DESC
) AS [roaming]
,(
SELECT TOP 1 [rent]
FROM tbl
WHERE [rent] IS NOT NULL
ORDER BY [id] DESC
) AS [rent]
I do it so
DECLARE #locale AS DECIMAL(11,2)
DECLARE #roaming AS DECIMAL(11,2)
DECLARE #rent AS DECIMAL(11,2)
SELECT #locale=COALESCE(locale, #locale), #roaming=COALESCE(roaming, #roaming), #rent=COALESCE(rent, #rent) FROM my_table
SELECT #locale as locale, #roaming as roaming, #rent as rent

SQL Pivot function for healthcare diagnosis codes

I'm trying to pivot data in my query (SQL Server 2008 R2) and I only need 2 columns pivoted but there may be up to 20 columns after the pivot. Here is my test data with up to 5 diagnosis codes:
pid DiagnosisCode
111 145.9
111 17.43
111 17.84
111 196.2
111 202.81
112 204.21
112 249.71
112 263.8
112 145.9
113 269.8
113 276.7
The output I'm trying to get looks like this:
pid | code1 | code2 | code3 | code4 | code5 | code6 | code... | code20
----------------------------------------------------------------------------
111 145.9 17.43 17.84 196.2 202.81 NULL NULL NULL
112 204.21 249.71 263.8 145.9 NULL NULL NULL NULL
113 269.8 276.7 NULL NULL NULL NULL NULL NULL
The code I have is :
select pid, DiagnosisCode
from
(select pid, DiagnosisCode, row_number() over(partition by pid order by pid)
as seq
from #temp
) as src
pivot
(min(DiagnosisCode)
for seq
in (DiagnosisCode)) pvt
For whatever reason, this function isn't clicking with me.I know that the MIN() aggregate function is required, but I don't need one in my output. I added the ROW_NUMBER() line so there would be a sequence field after reading one post, but I'm not sure why its needed. I've been reading all the other Pivot posts here and on other sites. I know this has been gone over many times on this site, but if you could help me understand what else I need in my query to get this to work I would be grateful.
You need to Fix your columns; the SQL Pivot table is different from Access, this is an example
declare #t as table (pid int , DiagnosisCode decimal(10,1))
insert #t select 111 , 145.9
insert #t select 111 , 17.43
insert #t select 111 , 17.84
insert #t select 111 , 196.2
insert #t select 111 , 202.81
insert #t select 112 , 204.21
insert #t select 112 , 249.71
insert #t select 112 , 263.8
insert #t select 112 , 145.9
insert #t select 113 , 269.8
insert #t select 113 , 276.7
select * from #t
select pid
,code1
,code2
,code3
,code4
,code5
,code6
,code7
,code8
,code9
,code10
,code11
,code12
,code13
,code14
,code15
,code16
,code17
,code18
,code19
,code20
from
(
select pid, DiagnosisCode, 'code' + cast(row_number() over(partition by pid order by pid) as varchar(2))
as seq
from #t
) as src
pivot
(min(DiagnosisCode)
for seq
in (
code1
,code2
,code3
,code4
,code5
,code6
,code7
,code8
,code9
,code10
,code11
,code12
,code13
,code14
,code15
,code16
,code17
,code18
,code19
,code20
)) pvt
pid code1 code2 code3 code4 code5 code6 code7 .... code20
---- ------ ------ ------- ------- ------ ------ ------ -------
111 145.9 17.4 17.8 196.2 202.8 NULL NULL NULL
112 204.2 249.7 263.8 145.9 NULL NULL NULL NULL
113 269.8 276.7 NULL NULL NULL NULL NULL NULL

Update multiple rows SQL Server 2008

Good day, I'm trying to update my table. Because there was an error(s) in my website. first Please check my table. (Penilaian_Header)
IdPenilaian | KodePenilaian | Nip | PositionCode | Total
1613 ----- 1603405 P028 0
1618 ----- 1602999 P028 0
1641 PE0001568 603060 P040 35
1640 PE0001567 1411862 P007 35
as you can see. There are two rows that KodePenilaian empty. So is there any chance to fill it ? so the result will be like this.
IdPenilaian | KodePenilaian | Nip | PositionCode | Total
1613 PE0001570 1603405 P028 0
1618 PE0001569 1602999 P028 0
1641 PE0001568 603060 P040 35
1640 PE0001567 1411862 P007 35
This how i generate KodePenilaian
select case
when right(max(KodePenilaian),7) is null then 'PE0000001'
else ('PE' + RIGHT('0000000' + cast(right(max(KodePenilaian),7) + 1 as nvarchar),7))
end KodePenilaian from Penilaian_Header
and here is there result when i run it
KodePenilaian
PE0001569
Thanks, Sorry for my bad english.
Not really used to sql server 2008
Try something like this:
update Penilaian_Header pen
set pen.KodePenilaian =
(select case
when right(max(newKode.KodePenilaian),7) is null then 'PE0000001'
else ('PE' + RIGHT('0000000' + cast(right(max(newKode.KodePenilaian),7) + 1 as nvarchar),7))
end KodePenilaian
from Penilaian_Header newKode)
where pen.KodePenilain = NULL
if ----- is NULL in your table
You can try this way...
;WITH cte
AS (SELECT *,
MAX(CONVERT(int, REPLACE(KodePenilaian, 'PE000', ''))) OVER () AS MaxNum,
ROW_NUMBER() OVER (ORDER BY kodePenilaian) AS rn
FROM YourTable)
UPDATE cte SET KodePenilaian = concat('PE000', maxnum + rn)
WHERE KodePenilaian IS NULL
Your table
create table YourTable (
IdPenilaian int, KodePenilaian varchar(20), Nip int, PositionCode varchar(10), Total INT)
insert into YourTable
(IdPenilaian , KodePenilaian , Nip , PositionCode , Total) values
( 1613 , NULL , 1603405 ,'P028', 0 )
,( 1618 , NULL , 1602999 ,'P028', 0 )
,( 1641 , 'PE0001568' , 603060 ,'P040', 35 )
,( 1640 , 'PE0001567' , 1411862 ,'P007', 35 )

Conditional display of calculated fields

I'm working on a table named FCT_HISTO_PORTES that contains ID_MVT_EXPL and ID_PTE fields which are integers. In this table a ID_MVT_EXPL is associated with one, two or three ID_PTE.
Here's an example:
select top 1000
ID_MVT_EXPL,
ID_PTE
from FCT_HISTO_PORTES
ID_MVT_EXPL ID_PTE
3945546 6
3945547 25
3945548 56
3945548 57
3945549 25
3945550 52
3945551 57
3945551 58
3945553 56
3945557 51
3945558 57
3945558 58
You can see that "3945546" has one ID_PTE and "3945548" has two different ID_PTE.
The aim of the game is that I can display a single line for each ID_MVT_EXPL with named fields ID_PTE_1, ID_PTE_2, ID_PTE_3.
I tried with this SELECT but the result is incorrect because all the ID_PTE fit into ID_PTE_1 and leave the other two to NULL.
select top 1000
ID_MVT_EXPL,
MIN(id_pte) as ID_PTE_1,
case
when COUNT(id_pte) = 2
then MAX(id_pte)
when COUNT(id_pte) = 3
then SUM(id_pte)-(MIN(ID_PTE)+MAX(ID_PTE))
end as ID_PTE_2,
case
when COUNT(id_pte) = 3
then MAX(id_pte)
end as ID_PTE_3
from FCT_HISTO_PORTES
group by ID_MVT_EXPL, ID_PTE
ID_MVT_EXPL ID_PTE_1 ID_PTE_2 ID_PTE_3
3945546 6 NULL NULL
3945547 25 NULL NULL
3945548 56 NULL NULL
3945548 57 NULL NULL
3945549 25 NULL NULL
3945550 52 NULL NULL
3945551 57 NULL NULL
3945551 58 NULL NULL
3945553 56 NULL NULL
3945557 51 NULL NULL
3945558 57 NULL NULL
3945558 58 NULL NULL
So what needs to change in my SELECT?
My suggestion is a little bit different. But if I understand you correct. You could do this:
Test data:
DECLARE #tbl TABLE(ID_MVT_EXPL INT, ID_PTE INT)
INSERT INTO #tbl
VALUES
(3945546,6),(3945547,25),(3945548,56),(3945548,57),
(3945549,25),(3945550,52),(3945551,57),(3945551,58),
(3945553,56),(3945557,51),(3945558,57),(3945558,58)
Query:
SELECT
pvt.ID_MVT_EXPL,
pvt.[1] AS ID_PTE_1,
pvt.[2] AS ID_PTE_2,
pvt.[3] AS ID_PTE_3
FROM
(
SELECT
ROW_NUMBER() OVER(PARTITION BY tbl.ID_MVT_EXPL ORDER BY ID_PTE) AS RowNbr,
tbl.ID_MVT_EXPL,
tbl.ID_PTE
FROM
#tbl AS tbl
) AS SourceTable
PIVOT
(
MAX(ID_PTE)
FOR RowNbr IN([1],[2],[3])
) AS pvt
Output:
3945546 6 NULL NULL
3945547 25 NULL NULL
3945548 56 57 NULL
3945549 25 NULL NULL
3945550 52 NULL NULL
3945551 57 58 NULL
3945553 56 NULL NULL
3945557 51 NULL NULL
3945558 57 58 NULL
Reference:
ROW_NUMBER (Transact-SQL)
Using PIVOT and UNPIVOT

Optimize time critical t-sql statement

I have a stored procedure and it is very slow, and i am not sure what i can improve.
The sql server table EntityValue only contains 1'800 rows.
here is the stored procedure:
CREATE PROCEDURE [dbo].[GetReportLabelValues](
#UnitIds UniqueIdentifierTableType readonly,
#LabelIds UniqueIdentifierTableType readonly)
AS
BEGIN
SELECT LabelValue.EntityId AS [LabelId], LabelValue.UnitId AS [UnitId], LabelValue.Value AS [Value]
FROM EntityValue, LabelValue
WHERE
EntityValue.IsDeleted = 0 AND
EntityValue.UnitId = LabelValue.UnitId AND
EntityValue.EntityId = LabelValue.EntityId AND
EXISTS (SELECT 1 FROM #UnitIds WHERE EntityValue.UnitId = [#UnitIds].Id) AND
EXISTS (SELECT 1 FROM #LabelIds WHERE EntityValue.EntityId = [#LabelIds].Id)
END;
What is wrong with this statement? Or do i need to set some additional indices?
Thank you for your help in advance :)
best
laurin
Edit:
Here is the excution plan:
DECLARE #unitIds AS UniqueIdentifierTableType;
INSERT INTO #unitIds ([Id]) VALUES ('63ABF15E-B8B0-4240-9B90-08F324D5179E') 1 1 0 NULL NULL 1 NULL 1 NULL NULL NULL 0.01000216 NULL NULL INSERT 0 NULL
|--Table Insert(OBJECT:(#unitIds), SET:([Id] = [Expr1004]), DEFINE:([Expr1004]={guid'63ABF15E-B8B0-4240-9B90-08F324D5179E'})) 1 2 1 Table Insert Insert OBJECT:(#unitIds), SET:([Id] = [Expr1004]), DEFINE:([Expr1004]={guid'63ABF15E-B8B0-4240-9B90-08F324D5179E'}) [Expr1004]={guid'63ABF15E-B8B0-4240-9B90-08F324D5179E'} 1 0.01 1E-06 9 0.01000216 NULL NULL PLAN_ROW 0 1
DECLARE #labelIds AS UniqueIdentifierTableType;
INSERT INTO #labelIds ([Id]) VALUES ('4E75B50C-E647-42E7-A87F-2D23D8B63D17') 2 3 0 NULL NULL 2 NULL 1 NULL NULL NULL 0.01000216 NULL NULL INSERT 0 NULL
|--Table Insert(OBJECT:(#labelIds), SET:([Id] = [Expr1004]), DEFINE:([Expr1004]={guid'4E75B50C-E647-42E7-A87F-2D23D8B63D17'})) 2 4 3 Table Insert Insert OBJECT:(#labelIds), SET:([Id] = [Expr1004]), DEFINE:([Expr1004]={guid'4E75B50C-E647-42E7-A87F-2D23D8B63D17'}) [Expr1004]={guid'4E75B50C-E647-42E7-A87F-2D23D8B63D17'} 1 0.01 1E-06 9 0.01000216 NULL NULL PLAN_ROW 0 1
exec dbo.GetReportLabelValues #unitIds, #labelIds 3 5 0 NULL NULL 3 NULL NULL NULL NULL NULL NULL NULL NULL EXECUTE PROC 0 NULL
CREATE PROCEDURE GetReportLabelValues(
#UnitIds UniqueIdentifierTableType readonly,
#LabelIds UniqueIdentifierTableType readonly)
AS
BEGIN
SELECT LabelValue.EntityId AS [LabelId], LabelValue.UnitId AS [UnitId], LabelValue.Value AS [Value]
FROM EntityValue, LabelValue
WHERE
EntityValue.IsDeleted = 0 AND
EntityValue.UnitId = LabelValue.UnitId AND
EntityValue.EntityId = LabelValue.EntityId AND
EXISTS (SELECT 1 FROM #UnitIds WHERE EntityValue.UnitId = [#UnitIds].Id) AND
EXISTS (SELECT 1 FROM #LabelIds WHERE EntityValue.EntityId = [#LabelIds].Id) 4 6 5 NULL NULL 5 NULL 1.062501 NULL NULL NULL 0.02785614 NULL NULL SELECT 0 NULL
|--Stream Aggregate(GROUP BY:([ABB_MDB2_Test].[dbo].[LabelValue].[UnitId], [ABB_MDB2_Test].[dbo].[LabelValue].[EntityId]) DEFINE:([ABB_MDB2_Test].[dbo].[LabelValue].[Value]=ANY([ABB_MDB2_Test].[dbo].[LabelValue].[Value]))) 4 8 6 Stream Aggregate Aggregate GROUP BY:([ABB_MDB2_Test].[dbo].[LabelValue].[UnitId], [ABB_MDB2_Test].[dbo].[LabelValue].[EntityId]) [ABB_MDB2_Test].[dbo].[LabelValue].[Value]=ANY([ABB_MDB2_Test].[dbo].[LabelValue].[Value]) 1.062501 0 1.062501E-06 343 0.02785614 [ABB_MDB2_Test].[dbo].[LabelValue].[UnitId], [ABB_MDB2_Test].[dbo].[LabelValue].[EntityId], [ABB_MDB2_Test].[dbo].[LabelValue].[Value] NULL PLAN_ROW 0 1
|--Nested Loops(Inner Join, OUTER REFERENCES:([ABB_MDB2_Test].[dbo].[EntityValue].[UnitId], [Id])) 4 9 8 Nested Loops Inner Join OUTER REFERENCES:([ABB_MDB2_Test].[dbo].[EntityValue].[UnitId], [Id]) NULL 1.062501 0 4.441255E-06 375 0.02785508 [ABB_MDB2_Test].[dbo].[EntityValue].[UnitId], [ABB_MDB2_Test].[dbo].[EntityValue].[EntityId], [ABB_MDB2_Test].[dbo].[LabelValue].[UnitId], [ABB_MDB2_Test].[dbo].[LabelValue].[EntityId], [ABB_MDB2_Test].[dbo].[LabelValue].[Value] NULL PLAN_ROW 0 1
|--Nested Loops(Inner Join, WHERE:([ABB_MDB2_Test].[dbo].[EntityValue].[EntityId]=[Id])) 4 10 9 Nested Loops Inner Join WHERE:([ABB_MDB2_Test].[dbo].[EntityValue].[EntityId]=[Id]) NULL 1.062501 0 0.0001594845 55 0.02455766 [ABB_MDB2_Test].[dbo].[EntityValue].[UnitId], [ABB_MDB2_Test].[dbo].[EntityValue].[EntityId], [Id] NULL PLAN_ROW 0 1
| |--Nested Loops(Inner Join, OUTER REFERENCES:([Id])) 4 12 10 Nested Loops Inner Join OUTER REFERENCES:([Id]) NULL 38.15419 0 0.0001594845 39 0.01814615 [ABB_MDB2_Test].[dbo].[EntityValue].[UnitId], [ABB_MDB2_Test].[dbo].[EntityValue].[EntityId] NULL PLAN_ROW 0 1
| | |--Sort(DISTINCT ORDER BY:([Id] ASC)) 4 13 12 Sort Distinct Sort DISTINCT ORDER BY:([Id] ASC) NULL 1 0.01126126 0.000100023 23 0.01464438 [Id] NULL PLAN_ROW 0 1
| | | |--Table Scan(OBJECT:(#UnitIds)) 4 14 13 Table Scan Table Scan OBJECT:(#UnitIds) [Id] 1 0.003125 0.0001581 23 0.0032831 [Id] NULL PLAN_ROW 0 1
| | |--Clustered Index Seek(OBJECT:([ABB_MDB2_Test].[dbo].[EntityValue].[PK_EntityValue]), SEEK:([ABB_MDB2_Test].[dbo].[EntityValue].[UnitId]=[Id]), WHERE:([ABB_MDB2_Test].[dbo].[EntityValue].[IsDeleted]=(0)) ORDERED FORWARD) 4 15 12 Clustered Index Seek Clustered Index Seek OBJECT:([ABB_MDB2_Test].[dbo].[EntityValue].[PK_EntityValue]), SEEK:([ABB_MDB2_Test].[dbo].[EntityValue].[UnitId]=[Id]), WHERE:([ABB_MDB2_Test].[dbo].[EntityValue].[IsDeleted]=(0)) ORDERED FORWARD [ABB_MDB2_Test].[dbo].[EntityValue].[UnitId], [ABB_MDB2_Test].[dbo].[EntityValue].[EntityId], [ABB_MDB2_Test].[dbo].[EntityValue].[IsDeleted] 38.15419 0.003125 0.0001989696 40 0.00332397 [ABB_MDB2_Test].[dbo].[EntityValue].[UnitId], [ABB_MDB2_Test].[dbo].[EntityValue].[EntityId], [ABB_MDB2_Test].[dbo].[EntityValue].[IsDeleted] NULL PLAN_ROW 0 1
| |--Table Scan(OBJECT:(#LabelIds)) 4 17 10 Table Scan Table Scan OBJECT:(#LabelIds) [Id] 1 0.0032035 7.96E-05 31 0.006240574 [Id] NULL PLAN_ROW 0 38.15419
|--Clustered Index Seek(OBJECT:([ABB_MDB2_Test].[dbo].[LabelValue].[PK_LabelValue]), SEEK:([ABB_MDB2_Test].[dbo].[LabelValue].[UnitId]=[ABB_MDB2_Test].[dbo].[EntityValue].[UnitId] AND [ABB_MDB2_Test].[dbo].[LabelValue].[EntityId]=[Id]) ORDERED FORWARD) 4 19 9 Clustered Index Seek Clustered Index Seek OBJECT:([ABB_MDB2_Test].[dbo].[LabelValue].[PK_LabelValue]), SEEK:([ABB_MDB2_Test].[dbo].[LabelValue].[UnitId]=[ABB_MDB2_Test].[dbo].[EntityValue].[UnitId] AND [ABB_MDB2_Test].[dbo].[LabelValue].[EntityId]=[Id]) ORDERED FORWARD [ABB_MDB2_Test].[dbo].[LabelValue].[UnitId], [ABB_MDB2_Test].[dbo].[LabelValue].[EntityId], [ABB_MDB2_Test].[dbo].[LabelValue].[Value] 1 0.003125 0.0001581 343 0.003292982 [ABB_MDB2_Test].[dbo].[LabelValue].[UnitId], [ABB_MDB2_Test].[dbo].[LabelValue].[EntityId], [ABB_MDB2_Test].[dbo].[LabelValue].[Value] NULL PLAN_ROW 0 1.062501
Try this, I converted the sub-queries to joins.
CREATE PROCEDURE [dbo].[GetReportLabelValues]
(
#UnitIds UniqueIdentifierTableType readonly,
#LabelIds UniqueIdentifierTableType readonly
)
AS
BEGIN
SELECT LabelValue.EntityId AS [LabelId],
LabelValue.UnitId AS [UnitId],
LabelValue.Value AS [Value]
FROM EntityValue
JOIN LabelValue ON EntityValue.UnitId = LabelValue.UnitId AND
EntityValue.EntityId = LabelValue.EntityId
JOIN #UnitID ON EntityValue.UnitId = [#UnitIds].Id
JOIN #LabelIds ON EntityValue.EntityId = [#LabelIds].Id
WHERE EntityValue.IsDeleted = 0
END;

Resources