Concatenating columns while pivoting - sql

My code is as below
SELECT
Customerid, CustomerName, [ftga.ihs.com] as ftga, [Email Delivery] as Email
FROM
(SELECT
Customerid, CustomerName, AliasName,
Deliverylocation,FTPUsername,FTPPassword
FROM
[dbo].[tblCustomerDeliveryServerMapping] t1
INNER JOIN
tblDeliveryServerDetails t2 ON t1.Deliveryserverid = t2.id
INNER JOIN
tblcustomerinfo t3 ON t1.customerid = t3.id) AS P
PIVOT
(MAX(Deliverylocation + FTPUsername + FTPPassword)
FOR AliasName in ([ftga.ihs.com],[Email Delivery])
) AS PVT
I want to concatenate FTPUsername and FTPPassword to Deliverylocation in the final result .
Above code is not working. If I remove +FTPUsername +FTPPassword, then the code works.
Can someone help ?

What if you do the concatenation in your subquery so that the column can be used in PIVOT
SELECT Customerid ,
CustomerName ,
[ftga.ihs.com] AS ftga ,
[Email Delivery] AS Email
FROM ( SELECT Customerid ,
CustomerName ,
AliasName ,
Deliverylocation ,
FTPUsername ,
FTPPassword ,
ConcatenatedValue = Deliverylocation + FTPUsername
+ FTPPassword
FROM [dbo].[tblCustomerDeliveryServerMapping] t1
INNER JOIN tblDeliveryServerDetails t2 ON t1.Deliveryserverid = t2.id
INNER JOIN tblcustomerinfo t3 ON t1.customerid = t3.id
) AS P PIVOT
( MAX(ConcatenatedValue) FOR AliasName IN ( [ftga.ihs.com],
[Email Delivery] ) ) AS PVT;

Related

Sql Join and Sum using Coalesce

select
COA.AccountNo
,AccountName
,(coalesce(DVDebit, 0) + coalesce(JVDebit, 0) + coalesce(CTDebit, 0)) as Debit
,(coalesce(CVCredit, 0) + coalesce(JVCredit, 0)) as Credit
from ChartOfAccounts as COA
left join
(
select
AccountNo
,sum(Credit) as CVCredit
from CreditVouchersBody
group by AccountNo
) as CreditVoucher
on COA.AccountNo = CreditVoucher.AccountNo
left join
(
select
AccountNo
,sum(Debit) as DVDebit
from DebitVouchersBody
group by AccountNo
) as DebitVoucher
on COA.AccountNo = DebitVoucher.AccountNo
left join
(
select
AccountNo
,sum(Debit) as JVDebit
,sum(Credit) as JVCredit
from JournalVouchersBody
group by AccountNo
) as JournalVoucher
on COA.AccountNo = JournalVoucher.AccountNo
left join
(
select
AccountNoPayTo
,sum(Amount) as CTDebit
from BankCheques
group by AccountNoPayTo
) as BankdCheque
on COA.AccountNo = BankdCheque.AccountNoPayTo
where
COA.IsDetailed = 'True'
and COA.AccountType = 'Expense';
This query was working fine and was taking values as per requirements. But now i have changed nothing in query but database values i changed, and this query is returning only 0. there are values in some tables in database. Can any one help me where i am wrong in this.
Does "returning only 0" means that it returns zero for the sums or do you mean that it doesn't return any rows?
If you mean that the sums are zero, then most likely the join doesn't work anymore. Have you changed the AccountNo in ChartOfAccounts or in the other tables?
If it doesn't return any rows, you have to check ChartOfAccounts, because the left joins won't reduce the number of rows you get.
If there are values in ChartOfAccounts, check the values of IsDetailed and AccountType and compare them against your where condition.
select distinct IsDetailed from ChartOfAccounts
select distinct AccountType from ChartOfAccounts
For the others: This is his query in a readable form:
select
COA.AccountNo
,AccountName
,(coalesce(DVDebit, 0) + coalesce(JVDebit, 0) + coalesce(CTDebit, 0)) as Debit
,(coalesce(CVCredit, 0) + coalesce(JVCredit, 0)) as Credit
from ChartOfAccounts as COA
left join
(
select
AccountNo
,sum(Credit) as CVCredit
from CreditVouchersBody
group by AccountNo
) as CreditVoucher
on COA.AccountNo = CreditVoucher.AccountNo
left join
(
select
AccountNo
,sum(Debit) as DVDebit
from DebitVouchersBody
group by AccountNo
) as DebitVoucher
on COA.AccountNo = DebitVoucher.AccountNo
left join
(
select
AccountNo
,sum(Debit) as JVDebit
,sum(Credit) as JVCredit
from JournalVouchersBody
group by AccountNo
) as JournalVoucher
on COA.AccountNo = JournalVoucher.AccountNo
left join
(
select
AccountNoPayTo
,sum(Amount) as CTDebit
from BankCheques
group by AccountNoPayTo
) as BankdCheque
on COA.AccountNo = BankdCheque.AccountNoPayTo
where
COA.IsDetailed = 'True'
and COA.AccountType = 'Expense';

SQL Group By issues with derived table

I'm attempting to create a table of all the latest payments made for an employee. The original table has all the payments made to an employee since they started. I created a derived table to give me only the records with the latest date in them.
I do still have some duplicates where the payment date is the same, in this case I want to add these payment together so they appear on one row instead.
Below is my working code;
SELECT T1.EmployeeCode
, T2.Staff_Number
, T2.Firstname + ' ' + T2.Surname AS Name
, T1.PaymentDate
, T1.p1
, T1.p2
, T1.p3
FROM DB1.dbo.PARTIFPSNI AS T1
--This section is supposed to return only the latest date
INNER JOIN (
SELECT EmployeeCode, MAX(PaymentDate) as MaxDate
FROM DB1.dbo.PARTIFPSNI
GROUP BY EmployeeCode
) T1A ON T1.EmployeeCode = T1A.EmployeeCode and T1.PaymentDate = T1A.MaxDate
LEFT JOIN DB2.dbo.Personnel_Records AS T2 ON (T1.EmployeeCode = T2.Staff_Number)
This returns the below;
I seem to have issues summing together p1, p2 & p3. I think this because I am trying to use the GROUP BY function twice.
SELECT T1.EmployeeCode ,
T2.Staff_Number ,
T2.Firstname + ' ' + T2.Surname AS Name ,
T1.PaymentDate ,
SUM(T1.p1) ,
SUM(T1.p2) ,
SUM(T1.p3)
FROM DB1.dbo.PARTIFPSNI AS T1
INNER JOIN ( SELECT EmployeeCode ,
MAX(PaymentDate) AS MaxDate
FROM DB1.dbo.PARTIFPSNI
GROUP BY EmployeeCode
) T1A ON T1.EmployeeCode = T1A.EmployeeCode
AND T1.PaymentDate = T1A.MaxDate
LEFT JOIN DB2.dbo.Personnel_Records AS T2 ON ( T1.EmployeeCode = T2.Staff_Number )
GROUP BY T1.EmployeeCode ,
T2.Staff_Number ,
T2.Firstname + ' ' + T2.Surname ,
T1.PaymentDate

Increment id value in SQL Server

In my SQL I have this query and I want to increase id with this insert that have
I don't want to use identity(1,1)
INSERT INTO dbo.tbl_waredetails
(wd_id, wd_mt_code, wd_wa_Id, wd_supply, wd_description, wd_status)
SELECT
(SELECT ISNULL(MAX(wd.wd_id), 0) + 1
FROM dbo.tbl_waredetails AS wd),
dbo.tbl_material.mat_code, #id,
dbo.fun_CompRem(mat_code, -1, #user_id) AS supply,
NULL, 0
FROM
tbl_material
INNER JOIN
dbo.tbl_MatUnit ON dbo.tbl_material.mat_MatUnt_Code = dbo.tbl_MatUnit.Matunt_code
INNER JOIN
dbo.tbl_MatGroup ON dbo.tbl_material.mat_MatGrp_Code = dbo.tbl_MatGroup.MatGrp_Code
but it send always 2 as id
Try below query
INSERT INTO dbo.tbl_waredetails
(wd_id, wd_mt_code, wd_wa_Id, wd_supply, wd_description, wd_status)
SELECT
(SELECT ISNULL(MAX(wd.wd_id), 0)
FROM dbo.tbl_waredetails AS wd)+ (row_number() over (order by wd.wd_id)),
dbo.tbl_material.mat_code, #id,
dbo.fun_CompRem(mat_code, -1, #user_id) AS supply,
NULL, 0
FROM
tbl_material
INNER JOIN
dbo.tbl_MatUnit ON dbo.tbl_material.mat_MatUnt_Code = dbo.tbl_MatUnit.Matunt_code
INNER JOIN
dbo.tbl_MatGroup ON dbo.tbl_material.mat_MatGrp_Code = dbo.tbl_MatGroup.MatGrp_Code
with cte as
(select (SELECT isnull(MAX(wd.wd_id),0) FROM dbo.tbl_waredetails ) as iden,dbo.tbl_material.mat_code,#id,
dbo.fun_CompRem(mat_code,-1,#user_id
)as supply,NULL,0
FROM tbl_material INNER JOIN
dbo.tbl_MatUnit ON dbo.tbl_material.mat_MatUnt_Code = dbo.tbl_MatUnit.Matunt_code INNER JOIN
dbo.tbl_MatGroup ON dbo.tbl_material.mat_MatGrp_Code = dbo.tbl_MatGroup.MatGrp_Code
where ROW_NUMBER ( )
OVER ( order by 1 )=1
union all
select c.iden+1,dbo.tbl_material.mat_code,#id,
dbo.fun_CompRem(mat_code,-1,#user_id
)as supply,NULL,0
FROM tbl_material INNER JOIN
dbo.tbl_MatUnit ON dbo.tbl_material.mat_MatUnt_Code = dbo.tbl_MatUnit.Matunt_code INNER JOIN
dbo.tbl_MatGroup ON dbo.tbl_material.mat_MatGrp_Code = dbo.tbl_MatGroup.MatGrp_Code
join cte as d on 1=1
where ROW_NUMBER ( )
OVER ( order by 1 )!=1
)
INSERT INTO dbo.tbl_waredetails
(
wd_id,
wd_mt_code ,
wd_wa_Id ,
wd_supply ,
wd_description ,
wd_status
)
SELECT iden, dbo.tbl_material.mat_code,#id,supply,NULL,0
FROM CTE

Trying to join two sql statement

I would like to join Query 1 and Query 2 on TripId.
Query 1
SELECT tblTrips.TripId,tblVehicles.VehicleNo
FROM tblTrips INNER JOIN tblVehicles ON tblTrips.VehicleId = tblVehicles.VehicleId
Query 2
;with T1 as (
SELECT tblTrips.TripId, tblTripDeductions.Amount, CONVERT(VARCHAR(400),tblDeductionTypes.DeductionType+' - '+tblTripDeductions.Description+' - '+ CONVERT(VARCHAR(24),tblTripDeductions.Amount)) as DeductionFor
FROM tblTrips INNER JOIN
tblTripDeductions ON tblTrips.TripId = tblTripDeductions.TripId INNER JOIN
tblDeductionTypes ON tblTripDeductions.DeductionId = tblDeductionTypes.DeductionId
)select **T1.TripId**, SUM(T1.Amount) as Amount, stuff((select '#',' ' + CONVERT(varchar(1000),T2.DeductionFor) from T1 AS T2 where T1.TripId = T2.TripId for xml path('')),1,1,'') [Description] from T1
Group by TripId
First query's output is list of TripId and VehicleNo.
Second query's output is list of TripId, Amount and description.
And my desire output is TripId, VehicleNo, amount and description.
The Syntax for WITH (Common Table Expressions) allows you to create multiple CTE's.
Using that you can turn your final part of Query2 in to a CTE (Which I'll name Query2) and your query for Query1 can also be made in to a CTE (which I'll name Query1).
Then, the final SELECT statement can simply join those two CTE's together.
;
WITH
T1 as (
SELECT tblTrips.TripId, tblTripDeductions.Amount, CONVERT(VARCHAR(400),tblDeductionTypes.DeductionType+' - '+tblTripDeductions.Description+' - '+ CONVERT(VARCHAR(24),tblTripDeductions.Amount)) as DeductionFor
FROM tblTrips INNER JOIN
tblTripDeductions ON tblTrips.TripId = tblTripDeductions.TripId INNER JOIN
tblDeductionTypes ON tblTripDeductions.DeductionId = tblDeductionTypes.DeductionId
)
,
Query2 AS (
select **T1.TripId**, SUM(T1.Amount) as Amount, stuff((select '#',' ' + CONVERT(varchar(1000),T2.DeductionFor) from T1 AS T2 where T1.TripId = T2.TripId for xml path('')),1,1,'') [Description] from T1
Group by TripId
)
,
Query1 AS (
<Your Code For Query1>
)
SELECT
*
FROM
Query1
INNER JOIN
Query2
ON Query1.TripID = Query2.TripID
I haven't don't anything to check your queries, as the layout that you have used isn't very readable.
Just merge the queries using CTE (didn't change/review your code, just formatted it for the sake of readability - input was pretty horrible to read)
;WITH T1 AS (
SELECT tblTrips.TripId
, tblTrips.DestinationDistrictId
, tblTrips.VehicleId
, tblTrips.No
, tblVehicles.VehicleNo
, tblTrips.CoachNo
, CONVERT(VARCHAR(24), tblTrips.GoDate, 105) AS GoDate
, tblTrips.GoTime
, CASE WHEN tblTrips.IsCome=1
THEN CONVERT(VARCHAR(24), tblTrips.ComeDate, 105)
ELSE '-'
END AS ComeDate
, CASE WHEN tblTrips.IsCome=1
THEN tblTrips.ComeTime
ELSE '-'
END AS ComeTime
, CASE WHEN tblTrips.IsCome=1
THEN (SD.DistrictName + ' - ' + DD.DistrictName + ' - ' + SD.DistrictName)
ELSE (SD.DistrictName + ' - ' + DD.DistrictName)
END AS Destination
, tblSupervisors.Name AS Supervisor
, tblDrivers.Name AS Driver
, tblTrips.AdvanceAmount
, tblTrips.AdvanceDescription
FROM tblTrips
INNER JOIN tblSupervisors ON tblTrips.SuperVisorId = tblSupervisors.SupervisorId
INNER JOIN tblDrivers ON tblTrips.DriverId = tblDrivers.DriverId
INNER JOIN tblDistricts SD ON tblTrips.StartDistrictId = SD.DistrictId
INNER JOIN tblDistricts DD ON tblTrips.DestinationDistrictId = DD.DistrictId
INNER JOIN tblVehicles ON tblTrips.VehicleId = tblVehicles.VehicleId
)
, Q1 AS (
SELECT T1.TripId
, SUM(T1.Amount) AS Amount
, STUFF((
SELECT '#', ' ' + CONVERT(VARCHAR(MAX), T2.DeductionFor)
FROM T1 AS T2
WHERE T1.TripId = T2.TripId FOR XML PATH(''))
,1,1,'') AS [Description]
FROM T1
GROUP BY TripId
)
, Q2 AS (
SELECT tblTrips.TripId
, tblTripDeductions.Amount
, CONVERT(VARCHAR(400), tblDeductionTypes.DeductionType + ' - ' + tblTripDeductions.Description + ' - ' + CONVERT(VARCHAR(24), tblTripDeductions.Amount)) AS DeductionFor
FROM tblTrips
INNER JOIN tblTripDeductions ON tblTrips.TripId = tblTripDeductions.TripId
INNER JOIN tblDeductionTypes ON tblTripDeductions.DeductionId = tblDeductionTypes.DeductionId
)
SELECT *
FROM Q1
INNER JOIN Q2 ON Q1.TripId = Q2.TripId

MSSQL Inner Join on Concatenated Column

I'm not a DBA so please don't yell at me. Trying to do an inner join and Group By using a concatenated column. The ON statement is producing a syntax error. I do not have access to the original tables and am trying to normalize this into another table, I know its ugly. Not overly worried about performance, just need to work. Cant use functions either.
SELECT DISTINCT A.[carrier_code],[carrier_name], [carrier_grouping], A.[collector_name], [dataset_loaded], [docnum], [envoy_payer_id], [loc], [market], [master_payor_grouping], [plan_class], [plan_name], A.[resp_ins],A.[resp_ind], A.[resp_payor_grouping], A.[Resp_Plan_Type], A.[rspphone], A.[state], A.[sys],A.[resp_ins]+A.[resp_payor_grouping]+A.[carrier_code]+A.[state]+A.[Collector_Name] as ExtId
FROM [Table1] A
INNER JOIN
(SELECT [resp_ins]+[resp_payor_grouping]+[carrier_code]+[state]+[Collector_Name] as Extid
FROM [Table1]
WHERE [resp_ind] = 'Insurance'
GROUP BY [resp_ins]+[resp_payor_grouping]+[carrier_code]+[state]+[Collector_Name]) B
ON A.[resp_ins]+A.[resp_payor_grouping]+A.[carrier_code]+A.[state]+A.[Collector_Name] = B.[resp_ins]+B.[resp_payor_grouping]+B.[carrier_code]+B.[state]+B.[Collector_Name];
My ON and Group By statements are eventually the primary key in new table.
Your alias B hasn't columns as you mentioned. It has just on column Extid.
SELECT DISTINCT A.[carrier_code],[carrier_name], [carrier_grouping], A.[collector_name], [dataset_loaded], [docnum], [envoy_payer_id], [loc], [market], [master_payor_grouping], [plan_class], [plan_name], A.[resp_ins],A.[resp_ind], A.[resp_payor_grouping], A.[Resp_Plan_Type], A.[rspphone], A.[state], A.[sys],A.[resp_ins]+A.[resp_payor_grouping]+A.[carrier_code]+A.[state]+A.[Collector_Name] as ExtId
FROM [Table1] A
INNER JOIN
(SELECT [resp_ins]+[resp_payor_grouping]+[carrier_code]+[state]+[Collector_Name] as Extid
FROM [Table1]
WHERE [resp_ind] = 'Insurance'
GROUP BY [resp_ins]+[resp_payor_grouping]+[carrier_code]+[state]+[Collector_Name]) B
ON A.[resp_ins]+A.[resp_payor_grouping]+A.[carrier_code]+A.[state]+A.[Collector_Name] = B.Extid;
Try this, I didn't put all the column in result, you can manage yourself.
select A.*
from
(
select [carrier_code],[carrier_name], [sys],[resp_ins]+[resp_payor_grouping]+[carrier_code]+[state]+[Collector_Name] as ExtId
FROM [Table1]
) A
inner join
(
select distinct Extid
from
(
SELECT [resp_ins]+[resp_payor_grouping]+[carrier_code]+[state]+[Collector_Name] as ExtId
FROM [Table1]
WHERE [resp_ind] = 'Insurance'
) ins
) B on (A.ExtId = B.ExtId)
You don't need to concatenate the values - you can GROUP BY and JOIN on multiple columns.
SELECT DISTINCT
...
FROM
[Table1] A
INNER JOIN
(
SELECT
[resp_ins],
[resp_payor_grouping],
[carrier_code],
[state],
[Collector_Name]
FROM
[Table1]
WHERE
[resp_ind] = 'Insurance'
GROUP BY
[resp_ins],
[resp_payor_grouping],
[carrier_code],
[state],
[Collector_Name]
) B
ON
(
A.[resp_ins] = B.[resp_ins]
Or
(A.[resp_ins] Is Null And B.[resp_ins] Is Null)
)
And
(
A.[resp_payor_grouping] = B.[resp_payor_grouping]
Or
(A.[resp_payor_grouping] Is Null And B.[resp_payor_grouping] Is Null)
)
And
(
A.[carrier_code] = B.[carrier_code]
Or
(A.[carrier_code] Is Null And B.[carrier_code] Is Null)
)
And
(
A.[state] = B.[state]
Or
(A.[state] Is Null And B.[state] Is Null)
)
And
(
A.[Collector_Name] = B.[Collector_Name]
Or
(A.[Collector_Name] Is Null And B.[Collector_Name] Is Null)
)
;