I am getting this error when I'm trying to getting data with the entity framework from the stored procedure.
Note: This stored procedure working fine when running it in the SQL server but throws an exception in the Entity framework.
The data reader is incompatible with the specified 'BuyMediaModel.GetSpendBreakdownofBuyer_Result'. A member of the type, 'Impressions', does not have a corresponding column in the data reader with the same name.
Here is my sp code.
ALTER Procedure [dbo].[GetSpendBreakdownofBuyer]
-- exec GetSpendBreakdownofBuyer '134', '2020'
#BuyerID varchar(100),
#Year varchar(20)
AS
BEGIN
SET FMTONLY OFF
SELECT
CASE WHEN
s.MediaType='Radio'
THEN 'Radio'
WHEN
s.MediaType='Newspaper' or s.MediaType='Magazine'
THEN 'Print'
WHEN
s.MediaType='TV'
THEN 'TV'
WHEN
s.MediaType='Podcast'
THEN 'Podcast'
WHEN
s.MediaType='OOH'
THEN 'OOH'
WHEN
s.MediaType='Digital'
THEN 'Digital'
ELSE 'Other'
END AS 'MediaType',
0 as Impressions,
Convert(char(3), od.AdvertisingDate, 0) as 'Month',
SUM(od.Price) as 'Budget_Spent'
INTO
#TempBreakdown
FROM
tblOrder o
JOIN
tblOrderDetail od
ON
o.Order_ID = od.Order_ID
JOIN
tblMediaSeller s
ON
s.MediaSeller_ID =od.Seller_ID
WHERE
o.Buyer_ID in (select cast(item as int) from dbo.SplitString(#BuyerID) )
AND YEAR(od.AdvertisingDate)=#Year
AND od.Status in ('Ordered','Approved')
GROUP BY
Convert(char(3), od.AdvertisingDate, 0),
s.MediaType
UNION
SELECT
'Other' as Mediatype,
0 as Impressions,
[Month],
Sum(BudgetSpent)
FROM
tblBudgetSpent
WHERE
Buyer_ID in (select cast(item as int) from dbo.SplitString(#BuyerID) )
AND [Year]=#Year
GROUP BY
[Month]
SELECT
SUM(Budget_Spent) AS Total,
--0 as Impressions,
[month]
INTO
#TempTotal
FROM
#TempBreakdown
GROUP BY
[month]
SELECT
b.MediaType,
0 as Impressions,
--CASE WHEN
-- t.Total <> 0
-- THEN((b.Budget_Spent/t.Total)*100)
-- ELSE
-- 0 END AS budget_spent,
b.Budget_Spent,
b.Month
FROM
#TempBreakdown b
JOIN
#TempTotal t
ON
b.Month=t.Month
UNION
SELECT
'Sales',
0 as Impressions,
Sales,
[Month]
FROM
tblSalesFigure
WHERE
BuyerID in (select cast(item as int) from dbo.SplitString(#BuyerID) )
AND Year=#Year
UNION
SELECT
'Impressions',
Impressions as Impressions,
0 ,
[Month]
FROM
tblMatrics
WHERE
Buyer_ID in (select cast(item as int) from dbo.SplitString(#BuyerID) )
AND Year=#Year
END
Related
This is an ASP.NET MVC project to execute stored procedure with input value, once we give input values, results will be shown in nested view. And the table doesn't have a primary key. So, while adding to Entity Framework, I am getting an error that I cannot add model designer to that stored procedure.
I haven't tried any code, because I am confused about how to add that stored procedure with table to project which is not having primary key.
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[CrystalBall_TAT_Computation]
(#Rescu_ID VARCHAR(20))
AS
BEGIN
-- Drop Temp Tables
IF OBJECT_ID('TempDB..#ClosedData','U') IS NOT NULL
DROP TABLE dbo.#ClosedData;
IF OBJECT_ID('TempDB..#OpenData','U') IS NOT NULL
DROP TABLE dbo.#OpenData;
IF OBJECT_ID('TempDB..#OpenData_RESCU_Group','U') IS NOT NULL
DROP TABLE dbo.#OpenData_RESCU_Group;
IF OBJECT_ID('TempDB..#OpenData_RESCU_GD_Group','U') IS NOT NULL
DROP TABLE dbo.#OpenData_RESCU_GD_Group;
IF OBJECT_ID('TempDB..#OpenData_PR_Count','U') IS NOT NULL
DROP TABLE dbo.#OpenData_PR_Count;
IF OBJECT_ID('TempDB..#OpenData_GD_Count','U') IS NOT NULL
DROP TABLE dbo.#OpenData_GD_Count;
IF OBJECT_ID('TempDB..#OpenRESCU_GD_Count','U') IS NOT NULL
DROP TABLE dbo.#OpenRESCU_GD_Count;
IF OBJECT_ID('TempDB..#OpenData_RESCU_Group_Sample','U') IS NOT NULL
DROP TABLE dbo.#OpenData_RESCU_Group_Sample;
IF OBJECT_ID('TempDB..#Final_Data','U') IS NOT NULL
DROP TABLE dbo.#Final_Data;
IF OBJECT_ID('TempDB..#GD_Level_Calc','U') IS NOT NULL
DROP TABLE dbo.#GD_Level_Calc;
IF OBJECT_ID('TempDB..#PR_Level_Calc','U') IS NOT NULL
DROP TABLE dbo.#PR_Level_Calc;
IF OBJECT_ID('TempDB..#Rescu_Level_Calc','U') IS NOT NULL
DROP TABLE dbo.#Rescu_Level_Calc;
IF OBJECT_ID('TempDB..#RESCU_Sample','U') IS NOT NULL
DROP TABLE dbo.#RESCU_Sample;
IF OBJECT_ID('TempDB..#OpenData_RESCU_Group_Sample_PR','U') IS NOT NULL
DROP TABLE dbo.#OpenData_RESCU_Group_Sample_PR;
IF OBJECT_ID('TempDB..#PR_Sample','U') IS NOT NULL
DROP TABLE dbo.#PR_Sample;
IF OBJECT_ID('TempDB..#OpenData_RESCU_Group_Sample_GD','U') IS NOT NULL
DROP TABLE dbo.#OpenData_RESCU_Group_Sample_GD;
IF OBJECT_ID('TempDB..#GD_Sample','U') IS NOT NULL
DROP TABLE dbo.#GD_Sample;
DECLARE #ReportDate DATE;
SELECT #ReportDate = MAX(CONVERT(DATE, Report_Date))
FROM dbo.Rescue_Daily_Assiginment_File;
-- Fetching relevant data from Open File for supplied RESCU ID
SELECT
A.NEW_RESCU_ID as RESCU_ID,
A.PAR_REQ_REF_NBR as PR_ID,
A.REQ_REF_NBR As GD_ID,
A.RGN_CD, A.ST_CD, A.SBJ_CD,
A.PRIMARYTRANSACTIONGROUP,
A.PLATFORMSIMPACTED_TEXT,
A.GENERAL_WORKTYPE,
A.ON_OFF,
CONVERT(DATE, A.GD_CRE_DT) AS GD_CRE_DT,
ISNULL(A.RGN_CD, '') + ISNULL(A.ST_CD, '') + ISNULL(A.SBJ_CD, '') + ISNULL(A.PRIMARYTRANSACTIONGROUP, '') + ISNULL(A.PLATFORMSIMPACTED_TEXT, '') + ISNULL(A.GENERAL_WORKTYPE, '') + ISNULL(A.ON_OFF, '') AS Combine_ID
INTO
dbo.#OpenData
FROM
dbo.Rescue_Daily_Assiginment_File AS A
WHERE
A.NEW_RESCU_ID IS NOT NULL
AND EXISTS (SELECT 1 FROM dbo.Rescue_Daily_Assiginment_File AS B
WHERE A.NEW_RESCU_ID = B.NEW_RESCU_ID AND B.ESCL_IND_CD LIKE 'RESCU%')
AND NEW_RESCU_ID = #Rescu_ID -- '19137-19137'
AND CONVERT(Date, A.Report_Date) = '2019-02-22' -- #ReportDate;
----------------
-- GD Count
SELECT
MIN(A.GD_CRE_DT) AS RESCU_Create_Date,
A.RESCU_ID,
A.PR_ID,
COUNT(A.GD_ID) AS Total_GDs
INTO
dbo.#OpenData_GD_Count
FROM
(SELECT
GD_CRE_DT, RESCU_ID, PR_ID, GD_ID
FROM
dbo.#OpenData
GROUP BY
GD_CRE_DT, RESCU_ID, PR_ID, GD_ID) AS A
GROUP BY
A.RESCU_ID, A.PR_ID;
-- PR Count
SELECT
MIN(GD_CRE_DT) AS RESCU_Create_Date,
A.RESCU_ID,
COUNT(PR_ID) AS Total_PRs,
MAX(Total_GDs) AS Total_GDs
INTO
dbo.#OpenData_PR_Count
FROM
(SELECT
GD_CRE_DT, RESCU_ID, PR_ID
FROM
dbo.#OpenData
GROUP BY
GD_CRE_DT, RESCU_ID, PR_ID) AS A
INNER JOIN
(SELECT
RESCU_ID, SUM(Total_GDs) AS Total_GDs
FROM
dbo.#OpenData_GD_Count
GROUP BY
RESCU_ID) AS B ON A.RESCU_ID = B.RESCU_ID
GROUP BY
A.RESCU_ID;
----------------
Select GD_CRE_DT, RESCU_ID, PR_ID, Combine_ID into dbo.#OpenData_RESCU_Group from dbo.#OpenData GROUP BY GD_CRE_DT, RESCU_ID, PR_ID, Combine_ID;
Select RESCU_ID, PR_ID, GD_ID, Combine_ID into dbo.#OpenData_RESCU_GD_Group from dbo.#OpenData GROUP BY RESCU_ID, PR_ID, GD_ID, Combine_ID;
--**************** CALCULATION **********************
SELECT A.RESCU_ID
, MAX(A.GD_CRE_DT) AS RESCU_Create_Date
, MAX(C.Total_PRs) AS Total_PRs
, MAX(C.Total_GDs) AS Total_GDs
, MAX(ISNULL(B.MIN_TAT, 0)) AS MIN_TAT
, MAX(ISNULL(B.MAX_TAT, 0)) AS MAX_TAT
INTO dbo.#Rescu_Level_Calc
FROM dbo.#OpenData_RESCU_Group AS A
LEFT JOIN dbo.ClosedDataResult AS B
ON A.Combine_ID = B.Combine_ID
INNER JOIN dbo.#OpenData_PR_Count AS C
ON A.RESCU_ID = C.RESCU_ID
GROUP BY A.RESCU_ID;
-- PR Level Output
SELECT A.RESCU_ID
, A.PR_ID
, MAX(C.Total_GDs) AS Total_GDs
, MAX(ISNULL(B.MIN_TAT, 0)) AS MIN_TAT
, MAX(ISNULL(B.MAX_TAT, 0)) AS MAX_TAT
INTO dbo.#PR_Level_Calc
FROM dbo.#OpenData_RESCU_GD_Group AS A
LEFT JOIN dbo.ClosedDataResult AS B
ON A.Combine_ID = B.Combine_ID
INNER JOIN dbo.#OpenData_GD_Count AS C
ON A.RESCU_ID = C.RESCU_ID
AND A.PR_ID = C.PR_ID
GROUP BY A.RESCU_ID, A.PR_ID;
-- GD Level Output
SELECT A.RESCU_ID
, A.PR_ID
, A.GD_ID
, MAX(ISNULL(B.MIN_TAT, 0)) AS MIN_TAT
, MAX(ISNULL(B.MAX_TAT, 0)) AS MAX_TAT
INTO dbo.#GD_Level_Calc
FROM dbo.#OpenData_RESCU_GD_Group AS A
LEFT JOIN dbo.ClosedDataResult AS B
ON A.Combine_ID = B.Combine_ID
GROUP BY A.RESCU_ID, A.PR_ID, A.GD_ID;
-- Output without Sample Size
--Select * from dbo.#Rescu_Level_Calc;
--Select * from dbo.#PR_Level_Calc;
--Select * from dbo.#GD_Level_Calc;
--=================================================
-- Get Distinct Combination from Closed Data for Provided Rescue ID at RESCU Leval
Select RESCU_ID
, Combine_ID
into dbo.#OpenData_RESCU_Group_Sample
from dbo.#OpenData
GROUP BY RESCU_ID, Combine_ID;
-- Get sum of Sample Size for Provided Rescue ID at RESCU Level
Select A.RESCU_ID
, SUM(ISNULL(B.SampleSize,0)) AS SampleSize
--, B.SampleSize
INTO dbo.#RESCU_Sample
FROM dbo.#OpenData_RESCU_Group_Sample AS A
LEFT JOIN dbo.ClosedDataResult AS B
ON A.Combine_ID = B.Combine_ID
GROUP BY A.RESCU_ID;
--------------------------------------------------
-- Get Distinct Combination from Closed Data for Provided Rescue ID at PR Leval
SELECT RESCU_ID
, PR_ID
, Combine_ID
INTO dbo.#OpenData_RESCU_Group_Sample_PR
FROM dbo.#OpenData
GROUP BY RESCU_ID, PR_ID, Combine_ID;
-- Get sum of Sample Size for Provided Rescue ID at PR Level
Select A.RESCU_ID
, A.PR_ID
, SUM(ISNULL(B.SampleSize,0)) AS SampleSize
INTO dbo.#PR_Sample
FROM dbo.#OpenData_RESCU_Group_Sample_PR AS A
LEFT JOIN dbo.ClosedDataResult AS B
ON A.Combine_ID = B.Combine_ID
GROUP BY A.RESCU_ID, A.PR_ID;
--------------------------------------------------
-- Get Distinct Combination from Closed Data for Provided Rescue ID at GD Leval
SELECT RESCU_ID
, PR_ID
, GD_ID
, Combine_ID
INTO dbo.#OpenData_RESCU_Group_Sample_GD
FROM dbo.#OpenData
GROUP BY RESCU_ID, PR_ID, GD_ID, Combine_ID;
-- Get sum of Sample Size for Provided Rescue ID at PR Level
Select A.RESCU_ID
, A.PR_ID
, A.GD_ID
, SUM(ISNULL(B.SampleSize,0)) AS SampleSize
INTO dbo.#GD_Sample
FROM dbo.#OpenData_RESCU_Group_Sample_GD AS A
LEFT JOIN dbo.ClosedDataResult AS B
ON A.Combine_ID = B.Combine_ID
GROUP BY A.RESCU_ID, A.PR_ID, A.GD_ID;
--=================================================
-- Final Output with Sample Size
-- RECSU LEVEL
Select A.RESCU_ID, A.RESCU_Create_Date, A.Total_PRs, A.Total_GDs, A.MIN_TAT, A.MAX_TAT, B.SampleSize
from dbo.#Rescu_Level_Calc AS A
LEFT JOIN dbo.#RESCU_Sample AS B
ON A.RESCU_ID = B.RESCU_ID;
-- PR LEVEL
Select A.RESCU_ID, A.PR_ID, A.Total_GDs, A.MIN_TAT, A.MAX_TAT, B.SampleSize
from dbo.#PR_Level_Calc AS A
LEFT JOIN dbo.#PR_Sample AS B
ON A.RESCU_ID = B.RESCU_ID
AND A.PR_ID = B.PR_ID;
-- GD LEVEL
Select A.RESCU_ID, A.PR_ID, A.GD_ID, A.MIN_TAT, A.MAX_TAT, B.SampleSize
from dbo.#GD_Level_Calc AS A
LEFT JOIN dbo.#GD_Sample AS B
ON A.RESCU_ID = B.RESCU_ID
AND A.PR_ID = B.PR_ID
AND A.GD_ID = B.GD_ID;
END
EXEC [dbo].[CrystalBall_TAT_Computation] '19993-19993'
Above is my stored procedure. How can I implement this?
This is the result of stored procedure
Hello i have the following query with a transaction in a try catch block and i rollback transaction on the catch block if fails. Problem is that I am creating a temporary table and i don't know how to handle it with a transaction. So how can I safely get rid of temporary table in this situation? I tried to add it on catch block but i'm not sure if this is a good practice
ALTER PROCEDURE GetDataForNewListaAbastecimento
#UAP NVARCHAR(20),
#ColaboradorId INT
AS
BEGIN
DECLARE #TransactionName nvarchar(20) = 'GetDataForNewListaAbastecimento'
DECLARE #Status INT
DECLARE #CurrentWeekDay INT
SET DATEFIRST 1
SET #CurrentWeekDay = DATEPART (WEEKDAY, GETDATE()) - 1
CREATE TABLE #tempTable
(
Id INT PRIMARY KEY,
Referencia NVARCHAR(15),
UAP NVARCHAR(20),
ConsumoWeek01 FLOAT,
ConsumoWeek02 FLOAT,
Stock INT,
QtdPecasPorCaixa INT
UNIQUE (Id)
)
BEGIN TRY
BEGIN TRAN #TransactionName
DECLARE #SQL NVARCHAR(MAX)
SELECT #SQL = 'INSERT INTO #tempTable
SELECT
Id,
Referencia,
UAP,
ConsumoWeek01 AS ConsumoWeek01,
ConsumoWeek02,
CASE
WHEN Stock IS NULL THEN 0
ELSE
Stock
END AS Stock,
QtdPecasPorCaixa
FROM OPENQUERY(MACPAC,
''WITH maxFornecedorByDate AS
(
SELECT
YDA3REP.A3ARCD,
YDA3REP.A3D5CD,
ROW_NUMBER() OVER ( PARTITION BY YDA3REP.A3D5CD ORDER BY YDA3REP.A3A3DT DESC) AS Number
FROM
AUTO.YSACHAPOR.YDA3REP YDA3REP
)
SELECT
ROW_NUMBER() OVER(ORDER BY A.RH6001 ASC) AS Id,
A.RH6001 as Referencia,
A.RH6002 as UAP,
A.RH6030 as ConsumoWeek01,
A.RH6031 as ConsumoWeek02,
IC130M.LLBLT1 as Stock,
M.AUQCON AS QtdPecasPorCaixa
FROM AUTO.D805DATPOR.TRP060H AS A
LEFT JOIN AUTO.D805DATPOR.IC130M IC130M
ON A.RH6001 = IC130M.LLPPN AND
IC130M.LLSTLC =
CASE A.RH6002
WHEN ''''UAP1'''' THEN ''''M1''''
WHEN ''''UAP2'''' THEN ''''M2''''
WHEN ''''UAP3'''' THEN ''''M3''''
WHEN ''''UAP4'''' THEN ''''M4''''
WHEN ''''UAP5'''' THEN ''''M5''''
WHEN ''''UAP6'''' THEN ''''M6''''
WHEN ''''UAPP'''' THEN ''''PROTOS''''
WHEN ''''EXT'''' THEN ''''EXTR''''
END
LEFT JOIN
(
SELECT
YDAUREP.AUD5CD,
YDAUREP.AUQCON
FROM maxFornecedorByDate F
join AUTO.YSACHAPOR.YDAUREP YDAUREP
ON F.A3ARCD = YDAUREP.AUARCD
AND F.A3D5CD = YDAUREP.AUD5CD
WHERE F.Number = 1 AND YDAUREP.AUD5CD LIKE ''''M%''''
AND YDAUREP.AUD5CD NOT LIKE ''''%P%''''
AND YDAUREP.AUA0NB > 1
AND YDAUREP.AUG6ST= ''''O''''
) M
ON M.AUD5CD = A.RH6001
WHERE A.RH6001 Not Like ''''FS%''''
AND A.RH6030 <> 0
AND A.RH6002 = ''''' + #UAP + ''''' '')'
EXEC sp_executesql #SQL
INSERT INTO hListasAbastecimento (UAP,DataCriacao,ColaboradorId) VALUES (#UAP,GETDATE(),#ColaboradorId)
INSERT INTO
hReferenciasAbastecimento
(
Referencia,
QtdAbastecimento,
QtdCaixas,
QtdPecasPorCaixa,
ListaAbastecimentoId
)
SELECT
C.Id,
C.Referencia,
( T.ConsumoWeek01 / ( ( P.NumDias - #CurrentWeekDay ) * P.NumPAB )) * P.AlcanceAbastecimento AS QtdAbastecimento,
T.QtdPecasPorCaixa,
CASE
WHEN ((T.ConsumoWeek01 / ( ( P.NumDias - #CurrentWeekDay ) * P.NumPAB )) * P.AlcanceAbastecimento) / NULLIF(T.QtdPecasPorCaixa,0) IS NULL THEN NULL
ELSE
CAST( CEILING(((T.ConsumoWeek01 / ( ( P.NumDias - #CurrentWeekDay ) * P.NumPAB )) * P.AlcanceAbastecimento) / T.QtdPecasPorCaixa ) AS INT)
END AS QtdCaixas,
SCOPE_IDENTITY()
FROM
#tempTable T
INNER JOIN hParametros P
ON P.Referencia = T.Referencia
AND P.UAP = #UAP
INNER JOIN hConsumos C
ON C.Referencia = P.Referencia
AND C.UAP = #UAP
WHERE T.Stock < ( T.ConsumoWeek01 / ( ( P.NumDias - #CurrentWeekDay ) * P.NumPAB )) * P.QtdMin
ORDER BY QtdAbastecimento DESC
COMMIT TRANSACTION #TransactionName
DROP TABLE #tempTable
-- Success, Lista de abastecimento foi criada sem errors --
SELECT #Status = 200
RETURN #Status
END TRY
BEGIN CATCH
IF ##TRANCOUNT > 0
ROLLBACK TRAN #TransactionName
DROP TABLE #tempTable
SELECT
ERROR_NUMBER() AS ErrorNumber,
ERROR_STATE() AS ErrorState,
ERROR_SEVERITY() AS ErrorSeverity,
ERROR_PROCEDURE() AS ErrorProcedure,
ERROR_LINE() AS ErrorLine,
ERROR_MESSAGE() AS ErrorMessage;
-- Erro, Nao foi possivel criar lista de abastecimento, verificar dynamic query --
SELECT #Status = 400
RETURN #Status
END CATCH
END
EDIT
I'm calling the SP from an Asp .NET Core application with Entity Framework Core
await _context.Database
.ExecuteSqlCommandAsync("EXEC #Status = GetDataForNewListaAbastecimento #UAP, #ColaboradorId", #params);
try add this:
IF OBJECT_ID('tempdb..#Results') IS NOT NULL DROP TABLE #Results
(Replace Name your temp table #Result)
I have a table like below
Name Year Bonus
---- ----- ------
Ram 2011 1000
Ram 2011 2000
Shyam 2011 'No Bonus'
Shyam 2012 5000
I want to display the total bonus year wise for each person.I tried below query
SELECT [Year],[Ram],[Shyam] FROM
(SELECT Name, [Year] , Bonus FROM Employee )Tab1
PIVOT
(
SUM(Bonus) FOR Name IN (Ram,Shyam)) AS Tab2
ORDER BY [Tab2].[Year]
My Output Should be like below
Name 2011 2012
---- ------ ------
Ram 3000 0
Shyam 'No Bonus' 5000
But it is not working.
Can anyone help me on this?
If your dbms is sql-server you can try to use SUM condition aggregate function in a CTE
then use CAST with coalesce to make it.
;WITH CTE AS(
SELECT Year,Name,
SUM(CASE WHEN Bonus LIKE '%[0-9]%' THEN CAST(Bonus AS DECIMAL) ELSE 0 END) total,
COUNT(CASE WHEN Bonus = 'No Bonus' THEN 1 END) cnt
FROM T
GROUP BY Year,Name
)
SELECT Name,
coalesce(MAX(CASE WHEN Year = 2011 THEN CAST(total AS VARCHAR(50)) END),'No Bonus') '2011',
coalesce(MAX(CASE WHEN Year = 2012 THEN CAST(total AS VARCHAR(50)) END),'No Bonus') '2012'
FROM CTE
GROUP BY Name
sqlfiddle
If you want to create columns dynamically you can try to use dynamic PIVOT.
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX);
;WITH CTE AS(
SELECT Year,Name,
SUM(CASE WHEN Bonus LIKE '%[0-9]%' THEN CAST(Bonus AS DECIMAL) ELSE 0 END) total,
COUNT(CASE WHEN Bonus = 'No Bonus' THEN 1 END) cnt
FROM T
GROUP BY Year,Name
)
SELECT #cols = STUFF((SELECT distinct ',coalesce(MAX(CASE WHEN cnt > 0 and Year = ' + cast(Year as varchar(5)) + ' THEN ''No Bonus'' WHEN Year = ' + cast(Year as varchar(5)) + ' and cnt = 0 THEN CAST(total AS VARCHAR(50)) END),''0'')' + QUOTENAME(Year)
FROM CTE c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = '
;WITH CTE AS(
SELECT Year,Name,
SUM(CASE WHEN Bonus LIKE ''%[0-9]%'' THEN CAST(Bonus AS DECIMAL) ELSE 0 END) total,
COUNT(CASE WHEN Bonus = ''No Bonus'' THEN 1 END) cnt
FROM T
GROUP BY Year,Name
)
SELECT Name, ' + #cols + '
from CTE
GROUP BY Name'
exec(#query)
sqlfiddle
According to your problem the following query is what I understood. Not the ideal solution but this will do.
You can modify the query if you need to make it dynamic.
SELECT [Name]
, case when [2011] = 0 then 'No Bonus' when [2011] is null then '0' else cast([2011] as varchar(50)) end as [2011]
, case when [2012] = 0 then 'No Bonus' when [2012] is null then '0' else cast([2012] as varchar(50)) end as [2012]
FROM
(SELECT Name, [Year] , cast(Bonus as int) Bonus FROM Employee)Tab1
PIVOT
(
SUM(Bonus) FOR Year IN ([2011],[2012])) AS Tab2
ORDER BY [Tab2].[Name]
You need to pass 0 in the table though and then modify in the PIVOT
I would just give up on storing numbers as strings. I don't see the difference between 0/NULL and 'No Bonus', except that the latter makes queries prone to really bad type conversion problems.
So, my advice is to do:
SELECT [Year],[Ram],[Shyam]
FROM (SELECT Name, [Year], TRY_CONVERT(int, Bonus) as Bonus
FROM Employee
) e
PIVOT (SUM(Bonus) FOR Name IN (Ram, Shyam)) AS Tab2
ORDER BY [Tab2].[Year] ;
You probably don't like that solution -- although I really do strongly recommend it because I have spent way too many hours debugging problems with numbers and dates stored as strings.
So, if you persist with storing values as string, use conditional aggregation and a bunch of logic:
select year,
coalesce( sum(case when name = 'Ram'
then convert(varchar(255), try_convert(int, bonus))
end),
'No Bonus'
) as Ram,
coalesce( sum(case when name = 'Shyam'
then convert(varchar(255), try_convert(int, bonus))
end),
'No Bonus'
) as Shyam
from employee e
group by year
order by year;
Assume i got the below row of number and max quantity value is 10.
Quantity BatchValue
2 0
4 0
4 0
6 1
8 2
Summation of 2+4+4 gives me a value less than or equal to max quatity 10 and so the batch value for those rows become 0. The pending rows are 6 and 8. They cannot be summed up to be < max quantity. So they will be seperate. Can we get an sql query or an algorith that can do this?
Here's a nice running sum routine you can use
create table #temp (rowid int identity, quantity int)
insert #temp
select quantity from yourtable order by your order
declare #holding table (quantity int, runningsum int)
declare #quantity int
declare #running int=0
declare #iterator int = 1
while #iterator<=(select max(rowid) from #temp)
begin
select #quantity=quantity from #temp where rowid=#iterator
set #running=#quantity+#running
insert #holding
select #quantity, #running
set #iterator=#iterator+1
end
Edited code from Daniel Marcus above to give the actual response requested in query.
CREATE TABLE #temp(rowid int identity(1,1), quantity int)
INSERT INTO #temp
SELECT 2
UNION ALL SELECT 4
UNION ALL SELECT 4
UNION ALL SELECT 6
UNION ALL SELECT 8
declare #batchValue int = 0 ,#maxquantity int = 10
declare #holding table (quantity int, batchvalue int)
declare #quantity int
declare #running int=0
declare #iterator int = 1
while #iterator<=(select max(rowid) from #temp)
begin
select #quantity=quantity from #temp where rowid=#iterator
set #running=#quantity+#running
-- Newly added condition
if (#running > #maxquantity) BEGIN
SET #batchValue = #batchValue + 1 -- increment the batch value
insert #holding select #quantity, #batchValue
SET #running = #quantity -- reset the running value
END
ELSE
insert #holding select #quantity, #batchValue
set #iterator=#iterator+1
end
SELECT * FROM #holding
DROP TABLE #temp
Hope the snippet works for your purpose. I tested this in SQL azure and provides the result you mentioned.
--The below query will help you if you working on sql server 2012 or higher
CREATE TABLE #RUN_TOT(ID INT)
INSERT INTO #RUN_TOT VALUES(2),(4),(4),(6),(8)
;WITH CTE AS
(
SELECT ID,
ROW_NUMBER() OVER(ORDER BY ID) RNUM,
CASE
WHEN SUM(ID) OVER(ORDER BY ID ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) <=
(SELECT MAX(ID) FROM #RUN_TOT) THEN 0
ELSE
ID
END VAL
FROM #RUN_TOT
)
SELECT ID,VAL FROM CTE WHERE VAL=0
UNION ALL
SELECT ID,ROW_NUMBER() OVER(ORDER BY VAL) VAL FROM CTE WHERE VAL<>0
I am trying to marge two rows and making single column. same data of row has to marge, and different data has to append to same row,
example:
I got result from joining three tables like this
uid name diseaseid intensity
1 xxxx 1 high
1 xxxx 2 low
Now I need final result like this
uid name diseaseid1 intensity diseaseid2 intensity
1 xxxx 1 high 2 low
Is there any option to make like this in Sql please help me out.
Thanks in advance.
Try this
CREATE TABLE #Table1
([uid] int, [name] varchar(4), [diseaseid] int, [intensity] varchar(4))
;
INSERT INTO #Table1
([uid], [name], [diseaseid], [intensity])
VALUES
(1, 'xxxx', 1, 'high'),
(1, 'xxxx', 2, 'low')
;
SELECT MAX([uid]) AS [uid]
,MAX([name]) AS [name]
,MAX([diseaseid1]) AS [diseaseid1]
,MAX([intensity1]) AS [intensity1]
,MAX([diseaseid2]) AS [diseaseid2]
,MAX([intensity2]) [intensity2]
FROM
(
SELECT [uid], [name]
, CASE WHEN rn=2 THEN NULL ELSE [diseaseid] END AS [diseaseid1]
, CASE WHEN rn=2 THEN NULL ELSE [intensity] END AS [intensity1]
, CASE WHEN rn=1 THEN NULL ELSE [diseaseid] END AS [diseaseid2]
, CASE WHEN rn=1 THEN NULL ELSE [intensity] END AS [intensity2]
FROM
(
SELECT [uid], [name], [diseaseid], [intensity],
ROW_NUMBER() OVER(PARTITION BY [uid] ORDER BY Name) AS rn
FROM #Table1
) T
) T
GROUP BY [uid], [name]
DROP TABLE #Table1
EIDT
Try this for dynamic columns
CREATE TABLE #Table1
([uid] int, [name] varchar(10), [diseaseid] int, [intensity] varchar(10))
INSERT INTO #Table1
([uid], [name], [diseaseid], [intensity])
VALUES
(1, 'xxxx', 1, 'high'),
(1, 'xxxx', 2, 'low'),
(1, 'xxxx', 3, 'medium')
DECLARE #MaxRows INT
DECLARE #CurrentRow INT
DECLARE #Query VARCHAR(MAX)
SET #CurrentRow = 1
SELECT #MaxRows = MAX(cnt) FROM (
SELECT COUNT(name) cnt FROM #Table1 GROUP BY [uid]
) AS T
SET #Query = '
SELECT MAX([uid]) AS [uid]
,MAX([name]) AS [name]'
WHILE #CurrentRow <= #MaxRows
BEGIN
SET #Query= #Query + '
,MAX(diseaseid'+CONVERT(VARCHAR(10),#CurrentRow)+') AS diseaseid'+CONVERT(VARCHAR(10),#CurrentRow)+''
SET #Query= #Query + '
,MAX(intensity'+CONVERT(VARCHAR(10),#CurrentRow)+') AS intensity'+CONVERT(VARCHAR(10),#CurrentRow)+''
SET #CurrentRow = #CurrentRow + 1
END
SET #Query= #Query + ' FROM
(
SELECT [uid], [name]'
SET #CurrentRow = 1
WHILE #CurrentRow <= #MaxRows
BEGIN
SET #Query= #Query + '
, CASE WHEN rn='+CONVERT(VARCHAR(10),#CurrentRow)+' THEN [diseaseid] ELSE NULL END AS diseaseid'+CONVERT(VARCHAR(10),#CurrentRow)+''
SET #Query= #Query + '
, CASE WHEN rn='+CONVERT(VARCHAR(10),#CurrentRow)+' THEN [intensity] ELSE NULL END AS intensity'+CONVERT(VARCHAR(10),#CurrentRow)+''
SET #CurrentRow = #CurrentRow + 1
END
SET #Query= #Query + ' FROM
(
SELECT [uid], [name], [diseaseid], [intensity],
ROW_NUMBER() OVER(PARTITION BY [uid] ORDER BY Name) AS rn
FROM #Table1
) T2
) T3
GROUP BY [uid], [name]'
PRINT (#Query)
EXEC (#Query)
DROP TABLE #Table1
You can use a query like this one
select *,(select col1,col2 from table2 where uid=t.uid) from table1 t
i think u're doing your joins wrong...
It looks like u're doing a Union of u're only grouping by UID, name.
Without knowing the join, the best advice i can give u is to try experiment with Right and Left outer join.
I think this should do what u want.
Try joining the table u get from the diseaseid twice, once with join and the second time with right outer join, this way u should get the diseaseid2 without problems.