Write SQL results back to same record - sql

I am using the following script to grab the value from DWNAME and split the value into 10 individuals values. What I need to do after that is take those 10 values and write them back to the SAME record to the COLUMN values that are listed as the Aliases. Is there a way to, within the same code, perform the record update?
WITH DOCUMENT_ID AS
(SELECT
DWDOCID,
VALUE,
ROW_NUMBER() OVER(partition by DWDOCID Order by DWDOCID) AS RowNum
FROM [dwdata].[dbo].[SUAM]
CROSS APPLY
STRING_SPLIT(DWNAME,'^')
WHERE DWDOCID > '3071822' AND DOCUMENT_TYPE IS NULL
)
SELECT DWDOCID,
[1] AS DRAWER,
[2] AS DOCID,
[3] AS STUDENTNUMBER,
[4] AS STUDENTID,
[5] AS LASTNAME,
[6] AS FIRSTNAME,
[7] AS FIELD5,
[8] AS DOCTYPE,
[9] AS CREATEDATE,
[10] AS DOCUMENTYEAR
FROM DOCUMENT_ID
PIVOT
(MAX(VALUE)
FOR RowNum in ([1], [2], [3], [4], [5], [6], [7], [8], [9], [10])) AS PVT

Simple update to your code
WITH DOCUMENT_ID AS
(SELECT
DWDOCID,
VALUE,
ROW_NUMBER() OVER(partition by DWDOCID Order by DWDOCID) AS RowNum
FROM [SUAM]
CROSS APPLY STRING_SPLIT(DWNAME,'^')
WHERE DWDOCID > '3071822' AND DOCUMENT_TYPE IS NULL
)
update suam
set drawer=t.drawer,docid=t.docid,studentnumber=t.studentnumber,studentid=t.studentid
,lastname=t.lastname,firstname=t.firstname,field5=t.field5
,createdate=t.createdate,documentyear=t.documentyear
from suam s inner join
(
SELECT DWDOCID,
[1] AS DRAWER,
[2] AS DOCID,
[3] AS STUDENTNUMBER,
[4] AS STUDENTID,
[5] AS LASTNAME,
[6] AS FIRSTNAME,
[7] AS FIELD5,
[8] AS DOCTYPE,
[9] AS CREATEDATE,
[10] AS DOCUMENTYEAR
FROM DOCUMENT_ID
PIVOT
(MAX(VALUE)
FOR RowNum in ([1], [2], [3], [4], [5], [6], [7], [8], [9], [10])) AS PVT
)t on s.dwdocid=t.dwdocid

Related

how to find first, second and third largest values from different columns in SQL

Hi I have a table with columns J1,J2,J3,J4,J5,J6,J7. I want to find the largest 3 values from these columns as L1,L2,L3.
I tried the below query to find the first largest
SELECT (
SELECT Max(v) FROM (
VALUES
([J1]), ([J2]),
([J3]), ([J4]),
([J5]), ([J6]),
([J7])
) AS value(v)
) as [L1]FROM dbo.JTable
If your table has a PK, say id, then you can use a query that employees UNPIVOT:
SELECT *
FROM (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY id ORDER BY Val) AS rn
FROM JTable
UNPIVOT (
Val FOR Col IN (J1, J2, J3, J4, J5, J6, J7)) AS unpvt) AS t
WHERE t.rn <= 3
If you want one row per id, then you can use PIVOT to undo the UNPIVOT operation:
SELECT id, [1], [2], [3]
FROM (
SELECT id, Val, rn
FROM (
SELECT id, Val, Col,
ROW_NUMBER() OVER (PARTITION BY id ORDER BY Val) AS rn
FROM JTable
UNPIVOT (
Val FOR Col IN (J1, J2, J3, J4, J5, J6, J7)) AS unpvt) AS t
WHERE t.rn <= 3) AS src
PIVOT (
MAX(Val) FOR rn IN ([1], [2], [3])) AS pvt

How to get multiple values from a singe query in sql

I have a query like:
SELECT NUM,
PARAM_1
FROM STOCK_CARD_PARAMETER WITH(NOLOCK)
WHERE FK_STOCK_CARD IN (SELECT FK_sTOCK_CARD
FROM STOCK_BARCODE WITH(NOLOCK)
WHERE BARCODE = '2002002232364' )
And it returns:
NUM PARAM_1
1 İNDİRİMSİZ
2 SEZON
3 UNISEXYETISKIN
I have to get a result like that. (side by side)
İNDİRİMSİZ SEZON UNISEXYETISKIN
To do this, I execute almost the same query 2 times like this:
INDIRIM = (SELECT PARAM_1
FROM STOCK_CARD_PARAMETER WITH(NOLOCK)
WHERE FK_STOCK_CARD IN (SELECT FK_sTOCK_CARD
FROM STOCK_BARCODE WITH(NOLOCK)
WHERE BARCODE = #BARKOD AND NUM = 1)),
STATU = ( SELECT PARAM_1
FROM STOCK_CARD_PARAMETER WITH(NOLOCK)
WHERE FK_STOCK_CARD IN (SELECT FK_sTOCK_CARD
FROM STOCK_BARCODE WITH(NOLOCK)
WHERE BARCODE = #BARKOD AND NUM = 2))
NUM column is the key here. How do I make this two query combined and get the result side by side?
Using PIVOT
SELECT [1], [2], [3]
FROM
(SELECT NUM, PARAM_1
FROM table) AS SourceTable
PIVOT
(
MAX(PARAM_1)
FOR NUM IN ([1], [2], [3])
) AS PivotTable;
Sample data with output
WITH C(NUM, PARAM_1) AS(
SELECT 1 , N'İNDİRİMSİZ' UNION ALL
SELECT 2 , N'SEZON' UNION ALL
SELECT 3 , N'UNISEXYETISKIN'
)
SELECT [1], [2], [3]
FROM
(SELECT NUM, PARAM_1
FROM C) AS SourceTable
PIVOT
(
MAX(PARAM_1)
FOR NUM IN ([1], [2], [3])
) AS PivotTable;
Output
İNDİRİMSİZ SEZON UNISEXYETISKIN

SQL server Pivot on Multiple Columns

I am trying to pivot on multiple columns. I am using SQL server 2008. Here is what I have tried so far
CREATE TABLE #t ( id int, Rscd varchar(10),Accd varchar(10),position int)
INSERT INTO #t Values (10,'A','B',1)
INSERT INTO #t Values (10,'C','D',2)
Select id,[1],[2],[11],[12] FROM
(SELECT id, Rscd,Accd, position , position +10 as Aposition
From #t)
As query
PIVOT (MAX(Rscd )
FOR Position IN ([1],[2])) AS Pivot1
PIVOT (MAX(Accd )
FOR Aposition IN ([11],[12])) AS Pivot2
The below indicated is the result that I am getting
id 1 2 11 12
10 NULL C NULL D
10 A NULL B NULL
But the result that I am trying to achieve is ,
id 1 2 11 12
10 A C B D
Any help ? what is wrong in my code.
I would unpivot the columns into pairs first, then pivot them. Basically the unpivot process will convert the pairs of columns (rscd, position and accd, aposition) into rows, then you can apply the pivot. The code will be:
select id, [1], [2], [11], [12]
from
(
select id, col, value
from #t
cross apply
(
select rscd, position union all
select Accd, position + 10
) c (value, col)
) d
pivot
(
max(value)
for col in ([1], [2], [11], [12])
) piv;
See SQL Fiddle with Demo
Select id,sum([1]),sum([2]),sum([11]),sum([12]) FROM
(SELECT id, Rscd,Accd, position , position +10 as Aposition
From #t)
As query
PIVOT (MAX(Rscd )
FOR Position IN ([1],[2])) AS Pivot1
PIVOT (MAX(Accd )
FOR Aposition IN ([11],[12])) AS Pivot2
group by id
Dont Use the ID Column. Use a derived table to retrieve all columns except the ID and then use the PIVOT table.

Horizontal Grand Total in Pivot Table SQL

I have this query working:
select cap_idPlanoContasFin , [3684],[2234],[2] ,
from
(
select cap_idPlanoContasFin,cap_idempresa,sum(cap_valorfatura)
as Stotal
from erp_ContasPagar
group by cap_idPlanoContasFin , cap_idEmpresa
) as sourcetable
pivot
(sum(Stotal)for cap_idEmpresa in ([3684],[2234],[2])
)as pivottable;
This query returns:
cap_idPlanoContasFin 3684 2234 2
3 9000 NULL NULL
10 1057840,68 NULL 1865081,35
11 NULL 7283,1 591,9
12 NULL NULL 178914,45
13 9305,07 1117,6 500
14 NULL 59333,5 34611,74
I want to put in the same query the Horizontal Total
Example:
cap_idPlanoContasFin 3684 2234 2 Total
---------------------------------------------------------------------
13 9305,07 1117,6 500 10922,67
How to make this? I have read something with UNION.
First of all, you don't need to group your data beforehand: the PIVOT clause will do that for you. So you can remove the GROUP BY clause and change the SUM()'s argument in PIVOT accordingly:
select cap_idPlanoContasFin, [3684], [2234], [2]
from
(
select cap_idPlanoContasFin, cap_idempresa, cap_valorfatura
from erp_ContasPagar
group by cap_idPlanoContasFin , cap_idEmpresa
) as sourcetable
pivot
(
sum(cap_valorfatura) for cap_idEmpresa in ([3684], [2234], [2])
) as pivottable;
To add a total column, you could use a window SUM() like this:
select cap_idPlanoContasFin, [3684], [2234], [2], Total
from
(
select cap_idPlanoContasFin, cap_idempresa, cap_valorfatura,
sum(cap_valorfatura) over (partition by cap_idPlanoContasFin) as Total
from erp_ContasPagar
) as sourcetable
pivot
(
sum(cap_valorfatura) for cap_idEmpresa in ([3684], [2234], [2])
) as pivottable;
Note, however, that if your sourcetable includes rows with cap_idEmpresa values other than those listed in the PIVOT clause, the corresponding cap_valorfatura values will be added up too. So you might want to filter the sourcetable row set before pivoting, like this:
select cap_idPlanoContasFin, [3684], [2234], [2], Total
from
(
select cap_idPlanoContasFin, cap_idempresa, cap_valorfatura,
sum(cap_valorfatura) over (partition by cap_idPlanoContasFin) as Total
from erp_ContasPagar
where cap_idempresa in (3684, 2234, 2)
) as sourcetable
pivot
(
sum(cap_valorfatura) for cap_idEmpresa in ([3684], [2234], [2])
) as pivottable;
Thanks to all , this is the final query :
select cap_idPlanoContasFin, plc_classificador, plc_nomeConta,[3684], [2234], [2],
isnull ([2234],0) + isnull ([2],0) AS Subtotal ,Total
from
(
select A.cap_idempresa, A.cap_idPlanoContasFin, A.cap_valorfatura,
B.plc_classificador , B.plc_nomeConta,
sum(A.cap_valorfatura) over (partition by A.cap_idPlanoContasFin) as Total
from erp_ContasPagar A /*where cap_idempresa in (3684, 2234, 2)*/
inner join tbl_PlanoFinanceiro B on A.cap_idPlanoContasFin = B.plc_id
) as sourcetable
pivot
(
sum(cap_valorfatura) for cap_idEmpresa in ([3684], [2234], [2])
) as pivottable;
I need use isnull to change NULL by o to sume subtotal . Thanks again by the help

what is wrong with this sql query using pivot

I am writing an sql query using pivot and I am getting following errors:
Msg 156, Level 15, State 1, Line 14
Incorrect syntax near the keyword 'select'.
Msg 102, Level 15, State 1, Line 14
Incorrect syntax near ')'.
and query I have written is :
select *
from (
select a.ID as id,
a.dataValue as value
from dbo.TableA a (nolock)
where a.ID in (select b.ID from dbo.TableB b(nolock))
and a.someOtherId = '4000'
and a.DT = '2/16/2011 12:00:00'
)as data
pivot
(
sum([value])
for [id] in (select ID from dbo.TableB (nolock))
) as pvt
Can anyone help me out on this?? Thanks in advance.
According to Microsoft's docs, you cannot use select after in: you must list the values manually.
[<column that contains the values that will become column headers>]
IN ( [first pivoted column], [second pivoted column],
... [last pivoted column])
) AS <alias for the pivot table>
Assuming that select b.ID from dbo.TableB b(nolock) returns 1,2,3, you can rewrite your code like this:
select *
from (
select a.ID as id,
a.dataValue as value
from dbo.TableA a (nolock)
where a.ID in (1,2,3)
and a.someOtherId = '4000'
and a.DT = '2/16/2011 12:00:00'
)as data
pivot
(
sum([value])
for [id] in ([1],[2],[3])
) as pvt
You cannot dynamically build the list of fields in the for in clause.
for [id] in (select ID from dbo.TableB (nolock))
This is not allowed. You must explicitly list the column names (Sorry)
Change: select ID from dbo.TableB
To: (Field1, field2, Field3) -- the actual names of the fields you want to return
Example:
-- Pivot table with one row and five columns
SELECT 'AverageCost' AS Cost_Sorted_By_Production_Days,
[0], [1], [2], [3], [4]
FROM
(SELECT DaysToManufacture, StandardCost
FROM Production.Product) AS SourceTable
PIVOT
(
AVG(StandardCost)
FOR DaysToManufacture IN ([0], [1], [2], [3], [4])
) AS PivotTable;