Related
In this query I cant understand what would be the proper syntax to PIVOT it by month and also display just top 10 records based on SUM(NetWrittenPremium).
;with cte_TopClasses
AS (
select
b.YearNum,
b.MonthNum,
REPLACE(ClassCode,'+','') + ' - '+ QLL.Description as Description,
SUM( Premium) as NetWrittenPremium
FROM tblCalendar b
LEFT JOIN ProductionReportMetrics prm ON b.MonthNum=Month(prm.EffectiveDate) AND b.YearNum = YEAR(EffectiveDate)
AND prm.EffectiveDate >=DateAdd(yy, -1, DATEADD(d, 1, EOMONTH(GETDATE()))) AND prm.EffectiveDate <= EOMONTH(GETDATE()) AND CompanyLine = 'Ironshore Insurance Company'
LEFT JOIN NetRate_Quote_Insur_Quote Q ON prm.NetRate_QuoteID = Q.QuoteID
LEFT JOIN NetRate_Quote_Insur_Quote_Locat QL ON Q.QuoteID = QL.QuoteID
LEFT JOIN (SELECT * FROM NetRate_Quote_Insur_Quote_Locat_Liabi nqI
JOIN ( SELECT LocationID as LocID, MAX(ClassCode) as ClCode
FROM NetRate_Quote_Insur_Quote_Locat_Liabi GROUP BY LocationID ) nqA
ON nqA.LocID = nqI.LocationID AND nqA.ClCode = nqI.ClassCode ) QLL
ON QLL.LocationID = QL.LocationID
WHERE ( b.YearNum = YEAR(GETDATE())-1 and b.MonthNum >= MONTH(GETDATE())+1 ) OR
( b.YearNum = YEAR(GETDATE()) and b.MonthNum <= MONTH(GETDATE()) )
GROUP BY b.YearNum,b.MonthNum,ClassCode, QLL.Description
)
SELECT
--TOP 10
RANK() OVER (ORDER BY NetWrittenPremium DESC) AS Rank, *
FROM cte_TopClasses
WHERE Description IS NOT NULL
ORDER BY NetWrittenPremium DESC,YearNum,MonthNum
The result should look something like that:
If I use the query below and then using matrics in SSRS to PIVOT it - then after grouping by Description it only displays me 2 Description.
;with cte_TopClasses
AS (
select
b.YearNum,
b.MonthNum,
REPLACE(ClassCode,'+','') + ' - '+ QLL.Description as Description,
SUM( Premium) as NetWrittenPremium
FROM tblCalendar b
LEFT JOIN ProductionReportMetrics prm ON b.MonthNum=Month(prm.EffectiveDate) AND b.YearNum = YEAR(EffectiveDate)
AND prm.EffectiveDate >=DateAdd(yy, -1, DATEADD(d, 1, EOMONTH(GETDATE()))) AND prm.EffectiveDate <= EOMONTH(GETDATE()) AND CompanyLine = 'Ironshore Insurance Company'
LEFT JOIN NetRate_Quote_Insur_Quote Q ON prm.NetRate_QuoteID = Q.QuoteID
LEFT JOIN NetRate_Quote_Insur_Quote_Locat QL ON Q.QuoteID = QL.QuoteID
LEFT JOIN (SELECT * FROM NetRate_Quote_Insur_Quote_Locat_Liabi nqI
JOIN ( SELECT LocationID as LocID, MAX(ClassCode) as ClCode
FROM NetRate_Quote_Insur_Quote_Locat_Liabi GROUP BY LocationID ) nqA
ON nqA.LocID = nqI.LocationID AND nqA.ClCode = nqI.ClassCode ) QLL
ON QLL.LocationID = QL.LocationID
WHERE ( b.YearNum = YEAR(GETDATE())-1 and b.MonthNum >= MONTH(GETDATE())+1 ) OR
( b.YearNum = YEAR(GETDATE()) and b.MonthNum <= MONTH(GETDATE()) )
GROUP BY b.YearNum,b.MonthNum,ClassCode, QLL.Description
)
SELECT *
FROM (SELECT RANK() OVER (ORDER BY NetWrittenPremium DESC) AS Rank, *
FROM cte_TopClasses
WHERE Description IS NOT NULL) AA
WHERE AA.Rank <= 10
ORDER BY AA.NetWrittenPremium DESC, AA.YearNum, AA.MonthNum
And the result of it in SSRS matrics :
You could try something like this at the end of the query, rather than what is there now:
SELECT *
FROM (SELECT RANK() OVER (ORDER BY [Description] DESC) AS Rank, *
FROM cte_TopClasses
WHERE Description IN (SELECT [Description]
FROM (SELECT RANK() OVER (ORDER BY SUM(NetWrittenPremium) DESC) AS [Rank], [Description], SUM(NetWrittenPremium) AS total
FROM cte_TopClasses
WHERE [Description] IS NOT NULL
GROUP BY [Description]) BB
WHERE [Rank] <= 10)) AA
ORDER BY YearNum, MonthNum
This wraps the query in a SELECT, and filters the ranked results to the 10 you want.
Then use a matrix in the report to pivot the results.
Using SQL Server 2012
I need to select TOP 10 Producer based on a ProducerCode. But the data is messed up, users were entering same Producers just spelled differently and with the same ProducerCode.
So I just need TOP 10, so if the ProducerCode is repeating, I just want to pick the first one in a list.
How can I achieve that?
Sample of my data
;WITH cte_TopWP --T
AS
(
SELECT distinct ProducerCode, Producer,SUM(premium) as NetWrittenPremium,
SUM(CASE WHEN PolicyType = 'New Business' THEN Premium ELSE 0 END) as NewBusiness1,
SUM(CASE WHEN PolicyType = 'Renewal' THEN Premium ELSE 0 END) as Renewal1,
SUM(CASE WHEN PolicyType = 'Rewrite' THEN Premium ELSE 0 END) as Rewrite1
FROM ProductionReportMetrics
WHERE YEAR(EffectiveDate) = 2016 AND TransactionType = 'Policy' AND CompanyLine = 'Arch Insurance Company'--AND ProducerType = 'Wholesaler'
GROUP BY ProducerCode,Producer
)
,
cte_Counts --C
AS
(
SELECT distinct ProducerCode, ProducerName, COUNT (distinct ControlNo) as Submissions2,
SUM(CASE WHEN QuotedPremium IS NOT NULL THEN 1 ELSE 0 END) as Quoted2,
SUM(CASE WHEN Type = 'New Business' AND Status IN ('Bound','Cancelled','Notice of Cancellation') THEN 1 ELSE 0 END ) as NewBusiness2,
SUM(CASE WHEN Type = 'Renewal' AND Status IN ('Bound','Cancelled','Notice of Cancellation') THEN 1 ELSE 0 END ) as Renewal2,
SUM(CASE WHEN Type = 'Rewrite' AND Status IN ('Bound','Cancelled','Notice of Cancellation') THEN 1 ELSE 0 END ) as Rewrite2,
SUM(CASE WHEN Status = 'Declined' THEN 1 ELSE 0 END ) as Declined2
FROM ClearanceReportMetrics
WHERE YEAR(EffectiveDate)=2016 AND CompanyLine = 'Arch Insurance Company'
GROUP BY ProducerCode,ProducerName
)
SELECT top 10 RANK() OVER (ORDER BY NetWrittenPremium desc) as Rank,
t.ProducerCode,
c.ProducerName as 'Producer',
NetWrittenPremium,
t.NewBusiness1,
t.Renewal1,
t.Rewrite1,
c.[NewBusiness2]+c.[Renewal2]+c.[Rewrite2] as PolicyCount,
c.Submissions2,
c.Quoted2,
c.[NewBusiness2],
c.Renewal2,
c.Rewrite2,
c.Declined2
FROM cte_TopWP t --LEFT OUTER JOIN tblProducers p on t.ProducerCode=p.ProducerCode
LEFT OUTER JOIN cte_Counts c ON t.ProducerCode=c.ProducerCode
You should use ROW_NUMBER to fix your issue.
https://msdn.microsoft.com/en-us/library/ms186734.aspx
A good example of this is the following answer:
https://dba.stackexchange.com/a/22198
Here's the code example from the answer.
SELECT * FROM
(
SELECT acss_lookup.ID AS acss_lookupID,
ROW_NUMBER() OVER
(PARTITION BY your_distinct_column ORDER BY any_column_you_think_is_appropriate)
as num,
acss_lookup.product_lookupID AS acssproduct_lookupID,
acss_lookup.region_lookupID AS acssregion_lookupID,
acss_lookup.document_lookupID AS acssdocument_lookupID,
product.ID AS product_ID,
product.parent_productID AS productparent_product_ID,
product.label AS product_label,
product.displayheading AS product_displayheading,
product.displayorder AS product_displayorder,
product.display AS product_display,
product.ignorenewupdate AS product_ignorenewupdate,
product.directlink AS product_directlink,
product.directlinkURL AS product_directlinkURL,
product.shortdescription AS product_shortdescription,
product.logo AS product_logo,
product.thumbnail AS product_thumbnail,
product.content AS product_content,
product.pdf AS product_pdf,
product.language_lookupID AS product_language_lookupID,
document.ID AS document_ID,
document.shortdescription AS document_shortdescription,
document.language_lookupID AS document_language_lookupID,
document.document_note AS document_document_note,
document.displayheading AS document_displayheading
FROM acss_lookup
INNER JOIN product ON (acss_lookup.product_lookupID = product.ID)
INNER JOIN document ON (acss_lookup.document_lookupID = document.ID)
)a
WHERE a.num = 1
ORDER BY product_displayheading ASC;
You could do this:
SELECT ProducerCode, MIN(Producer) AS Producer, ...
GROUP BY ProducerCode
I have the following SQL query on IBM DB2.
SUM(CASE
WHEN verzijaplaca.vpl_vrsteplacila = 9150 THEN
(select sum(verplaca.vpl_bruto)
from pet320.verzijaplaca as verplaca
)
ELSE 0
END) AS "brutoplacazaure"
The inner select works, but when I include it in CASE when it reports error.
ERROR: An operand of a column function is invalid.
DB2 SQL Error:
SQLCODE=-112, SQLSTATE=42607, SQLERRMC=null, DRIVER=3.57.91
Error
Code: -112
Also If I run only
SUM(CASE
WHEN verzijaplaca.vpl_vrsteplacila = 9150 THEN
(1.0)
ELSE 0
END) AS "brutoplacazaure"
it works
Any suggestions?? It seems that DB 2 doesn't support the inner sql in case when case or smth like that
Thank you
the whole sql query is the following
SELECT
zaposleni.za_koda AS "za_koda",
MAX(enotezpiz.ezp_rsza) AS "ezp_rsza",
MAX(zaposleni.za_polnoime) AS "za_polnoime",
MAX(verzije.ve_datnamena) AS "ve_datnamena",
MAX(verzije.ve_datizp) AS "ve_datizp",
MAX(opp_telefonodgos) AS "opp_telefonodgos",
MAX(pod_krajzaizpise ||', ') AS "pod_krajzaizpise",
MAX(racuni.ra_stracuna) AS "ra_stracuna",
MAX(racuni.ra_modul) AS "ra_modul",
MAX(racuni.ra_sklstev) AS "ra_sklstev",
MAX(verzije.ve_datizp) AS "ve_datizp",
MAX(verzije.ve_naziv) AS "ve_naziv",
SUM(CASE
WHEN vrsteplacila.vp_skupinevrpl in (1,2,3,4,16) and vrsteplacila.vp_udodatkov = 0 THEN verzijaplaca.vpl_eure
ELSE 0
END) AS "mfure",
MAX(dmzaposlenih.dmz_enotezpiz) AS "dmz_enotezpiz",
(select
SUM(olajsave.ozz_znesekolajsave) / 12
from
pet320.olajsavedczaposlenih as olajsave
INNER JOIN
pet320.verzije as verzija1
ON
olajsave.ooz_datumod <= verzija1.ve_datkm AND (olajsave.ooz_datumdo IS NULL OR olajsave.ooz_datumdo >= verzija1.ve_datzm)
INNER JOIN
pet320.zaposleni as zapp
ON
olajsave.ozz_zaposleni = zapp.za_id_za
INNER JOIN
pet320.VERZIJAPLACA as vpl
ON
vpl.vpl_verzije = verzija1.ve_id_ve
AND zapp.za_id_za = vpl.vpl_zaposleni
where
1=1
AND (vpl.vpl_vrsteplacila = 9150 OR vpl.vpl_skupinevrpl = 6)) AS "vz_znesvzddc",
SUM(CASE
WHEN vrsteplacila.vp_skupinevrpl = 3 AND vrsteplacila.vp_udodatkov = 0 THEN verzijaplaca.vpl_eure
WHEN vrsteplacila.vp_skupinevrpl = 4 AND vrsteplacila.vp_udodatkov = 1 THEN verzijaplaca.vpl_eure
ELSE
0
END) AS "bolovalure",
SUM(CASE
WHEN vrsteplacila.vp_skupinevrpl = 4 AND vrsteplacila.vp_udodatkov = 0 THEN verzijaplaca.vpl_eure
ELSE
0
END) AS "izostanekzdelaure",
SUM(CASE
WHEN vrsteplacila.vp_skupinevrpl = 3 THEN verzijaplaca.vpl_bruto
ELSE
0
END) AS "brutoznesekboleznine",
SUM(CASE WHEN vrsteplacila.vp_skupinevrpl = 16 THEN verzijaplaca.vpl_bruto
ELSE
0
END) AS "brutodopolnega",
SUM(CASE WHEN vrsteplacila.vp_skupinevrpl = 16 and vrsteplacila.vp_udodatkov = 0 THEN verzijaplaca.vpl_eure
ELSE
0
END) AS "uredopolenga",
SUM(CASE
WHEN vrsteplacila.vp_skupinevrpl IN (16) THEN (verzijaplaca.vpl_bruto - verzijaplaca.vpl_neto)
ELSE
0
END) AS "prispevkizasocvarnost",
SUM(CASE
WHEN vrsteplacila.vp_skupinevrpl IN (16) THEN verzijaplaca.vpl_akdohod
ELSE
0
END) AS "akdohodnine",
SUM(CASE
WHEN verzijaplaca.vpl_skupinevrpl IN (16) THEN verzijaplaca.vpl_neto - verzijaplaca.vpl_akdohod
ELSE
0
END) AS "netonadomestilo",
SUM(CASE WHEN verzijaplaca.vpl_vrsteplacila = 9150 THEN
(select sum(verplaca.vpl_bruto)
from pet320.verzijaplaca as verplaca
INNER JOIN
pet320.verzije as ver
ON
ver.ve_id_ve = verplaca.vpl_verzije
INNER JOIN
pet320.zaposleni as zapo
ON
zapo.za_id_za = verplaca.vpl_zaposleni
AND ver.ve_id_ve = verplaca.vpl_verzije
where verplaca.vpl_vrsteplacila in (select vp_id_vp from pet320.vrsteplacila where vp_skupinevrpl in (1,2))
and verplaca.vpl_zaposleni = zapo.za_id_za
and verplaca.vpl_verzije = ver.ve_id_ve)
ELSE 0
END) AS "brutoplacazaure"
FROM
pet320.verzijaplaca AS verzijaplaca
INNER JOIN
pet320.vrsteplacila AS vrsteplacila
ON
verzijaplaca.vpl_vrsteplacila = vrsteplacila.vp_id_vp
INNER JOIN
pet320.verzije AS verzije
ON
verzijaplaca.vpl_verzije = verzije.ve_id_ve
INNER JOIN
pet320.zaposleni AS zaposleni
ON
verzijaplaca.vpl_zaposleni = zaposleni.za_id_za
INNER JOIN
(SELECT
a.*
FROM
pet320.dmzaposlenih AS a
INNER JOIN
(SELECT
dmz_zaposleni,
MAX(dmz_datumod) AS max_dmz_datumod
FROM
pet320.dmzaposlenih
GROUP BY
dmz_zaposleni) AS b
ON
a.dmz_zaposleni = b.dmz_zaposleni
AND a.dmz_datumod = b.max_dmz_datumod) as dmzaposlenih
ON
dmzaposlenih.dmz_zaposleni = verzijaplaca.vpl_zaposleni
INNER JOIN
pet320.enotezpiz AS enotezpiz
ON
dmzaposlenih.dmz_enotezpiz = enotezpiz.ezp_id_ezp
LEFT JOIN
pet320.osnovnipodplace AS osnovnipodplace
ON
1=1
INNER JOIN
pet320.racuni AS racuni
ON
osnovnipodplace.opp_racuni = racuni.ra_id_ra
INNER JOIN
pet320.podjetja AS podjetja
ON
osnovnipodplace.opp_podjetja = podjetja.pod_id_pod
LEFT JOIN
pet320.verzijazaposleni AS verzijazaposleni
ON
verzijazaposleni.vz_zaposleni = zaposleni.za_id_za
AND verzijazaposleni.vz_verzije = verzije.ve_id_ve
INNER JOIN
pet320.verzijastrmesta as verzijastrmesta
ON
verzijastrmesta.vs_verzije = verzije.ve_id_ve
AND verzijastrmesta.vs_strmesta = dmzaposlenih.dmz_strmesta
INNER JOIN
pet320.verzijaorgenote AS verzijaorgenote
ON
verzijaorgenote.vo_verzije = verzije.ve_id_ve
AND verzijaorgenote.vo_orgenote = dmzaposlenih.dmz_orgenote
INNER JOIN
pet320.zaposinvalidi AS zaposinvalidi
ON
zaposinvalidi.zi_zaposleni = verzijaplaca.vpl_zaposleni and zi_datdo is null
INNER JOIN
pet320.verzijasumstavki AS verzijasumstavki
ON
verzijasumstavki.vss_verzije = verzijaplaca.vpl_verzije AND
verzijasumstavki.vss_zaposleni = verzijaplaca.vpl_zaposleni AND
verzijasumstavki.vss_vrsteplacila = 9301
WHERE
1=1
AND vrsteplacila.vp_skupinevrpl in (1,2,3,4,16)
AND (verzijaplaca.vpl_verzije = 215)
AND (verzijaplaca.vpl_zaposleni IS NULL OR 1=1)
AND (verzijaplaca.vpl_strm_strmesta IS NULL OR 1=1)
AND (dmzaposlenih.dmz_orgenote IS NULL OR 1=1)
AND (dmzaposlenih.dmz_izplacilnamesta IS NULL OR 1=1)
AND (verzijaplaca.vpl_placilnirazredi IS NULL OR 1=1)
AND (dmzaposlenih.dmz_vrstapog IN (1,0))
AND verzijaplaca.vpl_zaposleni in (select distinct vpl_zaposleni from pet320.verzijaplaca where vpl_skupinevrpl = 16 AND vpl_verzije = 215)
group by dmzaposlenih.dmz_enotezpiz,
zaposleni.za_koda
ORDER BY
dmzaposlenih.dmz_enotezpiz,
zaposleni.za_koda
INNER JOIN
(SELECT
a.*
FROM
pet320.dmzaposlenih AS a
INNER JOIN
(SELECT
dmz_zaposleni,
MAX(dmz_datumod) AS max_dmz_datumod
FROM
pet320.dmzaposlenih
GROUP BY
dmz_zaposleni) AS b
ON
a.dmz_zaposleni = b.dmz_zaposleni
AND a.dmz_datumod = b.max_dmz_datumod) as dmzaposlenih
ON
dmzaposlenih.dmz_zaposleni = verzijaplaca.vpl_zaposleni
INNER JOIN
pet320.enotezpiz AS enotezpiz
ON
dmzaposlenih.dmz_enotezpiz = enotezpiz.ezp_id_ezp
LEFT JOIN
pet320.osnovnipodplace AS osnovnipodplace
ON
1=1
INNER JOIN
pet320.racuni AS racuni
ON
osnovnipodplace.opp_racuni = racuni.ra_id_ra
INNER JOIN
pet320.podjetja AS podjetja
ON
osnovnipodplace.opp_podjetja = podjetja.pod_id_pod
LEFT JOIN
pet320.verzijazaposleni AS verzijazaposleni
ON
verzijazaposleni.vz_zaposleni = zaposleni.za_id_za
AND verzijazaposleni.vz_verzije = verzije.ve_id_ve
INNER JOIN
pet320.verzijastrmesta as verzijastrmesta
ON
verzijastrmesta.vs_verzije = verzije.ve_id_ve
AND verzijastrmesta.vs_strmesta = dmzaposlenih.dmz_strmesta
INNER JOIN
pet320.verzijaorgenote AS verzijaorgenote
ON
verzijaorgenote.vo_verzije = verzije.ve_id_ve
AND verzijaorgenote.vo_orgenote = dmzaposlenih.dmz_orgenote
INNER JOIN
pet320.zaposinvalidi AS zaposinvalidi
ON
zaposinvalidi.zi_zaposleni = verzijaplaca.vpl_zaposleni and zi_datdo is null
INNER JOIN
pet320.verzijasumstavki AS verzijasumstavki
ON
verzijasumstavki.vss_verzije = verzijaplaca.vpl_verzije AND
verzijasumstavki.vss_zaposleni = verzijaplaca.vpl_zaposleni AND
verzijasumstavki.vss_vrsteplacila = 9301
WHERE
1=1
AND vrsteplacila.vp_skupinevrpl in (1,2,3,4,16)
AND (verzijaplaca.vpl_verzije = 215)
AND (verzijaplaca.vpl_zaposleni IS NULL OR 1=1)
AND (verzijaplaca.vpl_strm_strmesta IS NULL OR 1=1)
AND (dmzaposlenih.dmz_orgenote IS NULL OR 1=1)
AND (dmzaposlenih.dmz_izplacilnamesta IS NULL OR 1=1)
AND (verzijaplaca.vpl_placilnirazredi IS NULL OR 1=1)
AND (dmzaposlenih.dmz_vrstapog IN (1,0))
AND verzijaplaca.vpl_zaposleni in (select distinct vpl_zaposleni from pet320.verzijaplaca where vpl_skupinevrpl = 16 AND vpl_verzije = 215)
group by dmzaposlenih.dmz_enotezpiz,
zaposleni.za_koda
ORDER BY
dmzaposlenih.dmz_enotezpiz,
zaposleni.za_koda
The query as you tried to write it would run
select sum(verplaca.vpl_bruto)
from pet320.verzijaplaca as verplaca
and produce the exact same result every time the case statement was true. Even if you can do it that way, you shouldn't, because it's a huge waste of time to run that query over and over. Instead, run that statement once and store the value. Then refer to the stored value whenever you need it. Here are a couple of options:
with vpl_bruto_sum as (
select sum(verplaca.vpl_bruto) as total
from pet320.verzijaplaca as verplaca
)
select sum(case when verzijaplaca.vpl_vrsteplacila = 9150
then vpl_bruto_sum.total else 0
end
)
from pet320.verzijaplaca
inner join vpl_bruto_sum on 1=1;
Or you could make thinks simpler by using the join condition instead of the inner case statement:
with vpl_bruto_sum as (
select sum(verplaca.vpl_bruto) as total
from pet320.verzijaplaca as verplaca
)
select sum(vpl_bruto_sum.total)
from pet320.verzijaplaca
left outer join vpl_bruto_sum on verzijaplaca.vpl_vrsteplacila = 9150;
If you want to calculate a value, then use it in multiple different queries, you could use a variable:
create or replace variable my_sum integer;
set my_sum = (select sum(vpl_bruto) from pet320.verzijaplaca);
select sum(case when verzijaplaca.vpl_vrsteplacila = 9150
then my_sum else 0
end
)
from pet320.verzijaplaca;
Hopefully that will help you get started.
It looks like there are probably other problems with your query as well. For example, where 1=1 and... is not a useful construct. It might be worth seeking help about how to design a better query--I think it could be a lot simpler, though it's hard to say without knowing what you are doing.
I have select, iside select have 2 column. This column must be filled from same select, but I don't want use select twice for it. Is it possoble use select 1 time and after that set second column value from first?
Example:
insert into #temptable from
select
a = (select aa from table1 where quantity > 5)
b = (select aa from table1 where quantity > 5)
I need:
insert into #temptable from
select
a = (select aa from table1 where quantity > 5)
b = {value from a}
Update. I wrote bad example, I need set to BalancePrediction1 and BalancePrediction2 value from Balance
INSERT #tmpBalances
SELECT PA.ContractId AS 'ContractId',
Con.Name AS 'ContractName',
Bal.PortfolioAccountId AS 'PortfolioAccountId',
PA.Name AS 'PortfolioAccountName',
RA.GeneralId AS 'RegisterAccountGeneralId',
Bal.BalanceTypeId AS 'BalanceTypeId',
Bt.Name AS 'BalanceTypeName',
Bt.Type AS 'BalanceTypeType',
Bal.BalanceTimeType AS 'BalanceTimeType',
Bal.InstrumentId AS 'InstrumentId',
Ins.Name AS 'InstrumentName',
Ins.GeneralId AS 'InstrumentGeneralId',
(Bal.Balance -
(
SELECT COALESCE(SUM(Mov.Amount), 0)
FROM trd.Movements AS Mov
WHERE
Bal.InstrumentId = Mov.InstrumentId AND
Bal.PortfolioAccountId = Mov.PortfolioAccountId AND
Bal.BalanceTypeId = Mov.BalanceTypeId AND
Bal.BalanceTimeType = Mov.BalanceTimeType AND
DateDiff(DAY, #Date, Mov.Date) > 0 AND
-- Currency může být null a NULL = NULL nejde
COALESCE(Bal.CurrencyId, -1) = COALESCE(Mov.CurrencyId, -1)
)
) as Balance,
Balance AS 'BalancePrediction1',
Balance AS 'BalancePrediction2',
Bal.CurrencyId AS 'CurrencyId',
Ccy.Code AS 'CurrencyCode',
PA.PositionServiceType 'PositionServiceType',
Ccy.Name 'CurrencyName',
S.Nominal AS 'Nominal',
S.NominalCurrencyId AS 'NominalCurrencyId',
trd.GetCurrencyCode(S.NominalCurrencyId) AS 'NominalCurrencyCode'
FROM trd.Balances AS Bal
JOIN trd.PortfolioAccounts AS PA ON PA.Id = Bal.PortfolioAccountId
JOIN trd.Contracts AS Con ON Con.Id = PA.ContractId
JOIN trd.RegisterAccounts AS RA ON RA.Id = PA.RegisterAccountId
JOIN trd.BalanceTypes AS Bt ON Bt.Id = Bal.BalanceTypeId
JOIN trd.Instruments AS Ins ON Ins.Id = Bal.InstrumentId
LEFT OUTER JOIN trd.Currencies AS Ccy ON Ccy.Id = Bal.CurrencyId
LEFT JOIN trd.SecuritiesView S ON s.Id = Ins.Id AND DateDiff(d, S.ValidFrom, #Date) >= 0 AND (S.ValidTo IS NULL OR DateDiff(d, S.ValidTo, #Date) < 0)
AND S.InstrumentInstrumentTypePriceUnit = 1
You could do an update to the table variable after the insert.
update #tmpBalances
set BalancePrediction1 = Balance,
BalancePrediction2 = Balance
Or you can use cross apply to calculate the sum.
INSERT #tmpBalances
SELECT PA.ContractId AS 'ContractId',
Con.Name AS 'ContractName',
Bal.PortfolioAccountId AS 'PortfolioAccountId',
PA.Name AS 'PortfolioAccountName',
RA.GeneralId AS 'RegisterAccountGeneralId',
Bal.BalanceTypeId AS 'BalanceTypeId',
Bt.Name AS 'BalanceTypeName',
Bt.Type AS 'BalanceTypeType',
Bal.BalanceTimeType AS 'BalanceTimeType',
Bal.InstrumentId AS 'InstrumentId',
Ins.Name AS 'InstrumentName',
Ins.GeneralId AS 'InstrumentGeneralId',
(Bal.Balance - Mov.SumAmount) AS Balance,
(Bal.Balance - Mov.SumAmount) AS 'BalancePrediction1',
(Bal.Balance - Mov.SumAmount) AS 'BalancePrediction2',
Bal.CurrencyId AS 'CurrencyId',
Ccy.Code AS 'CurrencyCode',
PA.PositionServiceType 'PositionServiceType',
Ccy.Name 'CurrencyName',
S.Nominal AS 'Nominal',
S.NominalCurrencyId AS 'NominalCurrencyId',
trd.GetCurrencyCode(S.NominalCurrencyId) AS 'NominalCurrencyCode'
FROM trd.Balances AS Bal
JOIN trd.PortfolioAccounts AS PA ON PA.Id = Bal.PortfolioAccountId
JOIN trd.Contracts AS Con ON Con.Id = PA.ContractId
JOIN trd.RegisterAccounts AS RA ON RA.Id = PA.RegisterAccountId
JOIN trd.BalanceTypes AS Bt ON Bt.Id = Bal.BalanceTypeId
JOIN trd.Instruments AS Ins ON Ins.Id = Bal.InstrumentId
LEFT OUTER JOIN trd.Currencies AS Ccy ON Ccy.Id = Bal.CurrencyId
LEFT JOIN trd.SecuritiesView S ON s.Id = Ins.Id AND DateDiff(d, S.ValidFrom, #Date) >= 0 AND (S.ValidTo IS NULL OR DateDiff(d, S.ValidTo, #Date) < 0)
AND S.InstrumentInstrumentTypePriceUnit = 1
CROSS APPLY (SELECT COALESCE(SUM(Mov.Amount), 0)
FROM trd.Movements AS Mov
WHERE
Bal.InstrumentId = Mov.InstrumentId AND
Bal.PortfolioAccountId = Mov.PortfolioAccountId AND
Bal.BalanceTypeId = Mov.BalanceTypeId AND
Bal.BalanceTimeType = Mov.BalanceTimeType AND
DateDiff(DAY, #Date, Mov.Date) > 0 AND
-- Currency může být null a NULL = NULL nejde
COALESCE(Bal.CurrencyId, -1) = COALESCE(Mov.CurrencyId, -1)
) Mov(SumAmount)
SELECT aa AS a, aa AS b
FROM table1
WHERE quantity > 5
One way;
;with T (value) as (
select aa from table1 where quantity > 5
)
insert into #temptable
select value, value from T
I have the following code which works FANTASTIC. Except - It is a sub-query to another (final) outer query and when I attempt to encapsulate this as a sub-query it refuses to run. To make it simple, I just did a "SELECT * FROM ( MY QUERY HERE)" and that even fails to run. I can only figure I am putting the right ")" in the wrong spot, but I just don't know....
Anyway - this is the query that runs fine till it is a simple sub-query:
SELECT FK_Campaign, FK_Geography, FK_InvoiceDate, FK_SalesType, FK_CustGroup, FK_Customer_Detail, FK_Parent_Detail, FK_Department, FK_Item_Detail,
FK_ItemClass_Detail, FK_ItemGroup_Detail, FK_SalesRep, FK_SalesOrigin, FK_QualityCode, FK_QualityDetailCode, FK_ResponsibilityCode,
FK_NewItemFlag, FK_TransDate, FK_CreatedDate, FK_VMReceivedDate, FK_ReturnAction, FK_StatusCode, ABC.InvoiceId, SalesID, VMRaNumber,
RetDays, ReturnQty, LineAmountmst, Qty, ReturnDays, ReturnLineAmount, ListPrice, ABC.InventTransId, ABC.ItemId,
ZZZ.FK_InventSerialProdDate AS FK_InventSerialProdDate
FROM
(SELECT
ISNULL((SELECT campaignkey --PK_Campaign
FROM VMDWAnalytical.DBO.DIM_Campaign
WHERE CampaignID = ST.smmCampaignID), -99) FK_Campaign,
ISNULL((SELECT PK_Geography
FROM VMDWAnalytical.DBO.DIM_Geography G
WHERE G.Country = ISNULL(CIJ.DLVCountryRegionID, 'zUnknown')
AND G.State = ISNULL(CIJ.DLVState, 'zUnknown')
AND G.Zip = ISNULL(CIJ.DLVZipCode, 'zUnknown')), -99) FK_Geography,
ISNULL((SELECT T.TIMEKEY
FROM VMDWAnalytical.DBO.DIM_Time T
WHERE T.FullDate = CIJ.InvoiceDate), 1) FK_InvoiceDate,
ISNULL((SELECT PK_SalesType
FROM VMDWAnalytical.DBO.DIM_SalesType
WHERE SalesType = SL.SalesType), -99) FK_SalesType,
ISNULL((SELECT PK_CustGroup
FROM VMDWAnalytical.DBO.DIM_CustGroup
WHERE CustGroup = CT.CustGroup), -99) FK_CustGroup,
ISNULL((SELECT PK_Customer_Detail
FROM VMDWAnalytical.DBO.DIM_Customer_Detail
WHERE AccountNum = CIJ.OrderAccount), -99) FK_Customer_Detail,
ISNULL((SELECT PK_Parent_Detail
FROM VMDWAnalytical.DBO.DIM_Parent_Detail
WHERE AccountNum = CIJ.OrderAccount), -99) FK_Parent_Detail,
ISNULL((SELECT PK_Department
FROM VMDWAnalytical.DBO.DIM_Department D
WHERE D.NUM = CIT.Dimension), -99) FK_Department,
ISNULL((SELECT PK_Item_Detail
FROM VMDWAnalytical.dbo.DIM_Item_Detail
WHERE Item = IT.ItemID
AND (ConfigID = ID.ConfigID
OR ConfigID = 'NONE')), -99) FK_Item_Detail,
ISNULL((SELECT PK_ItemClass_Detail
FROM VMDWAnalytical.dbo.DIM_ItemClass_Detail
WHERE ItemID = IT.ItemID), -99) FK_ItemClass_Detail,
ISNULL((SELECT PK_ItemGroup_Detail
FROM VMDWAnalytical.dbo.DIM_ItemGroup_Detail
WHERE ItemID = IT.ItemID), -99) FK_ItemGroup_Detail,
ISNULL((SELECT PK_SalesRep
FROM VMDWAnalytical.DBO.DIM_SalesRep
WHERE SalesRep = ST.SalesResponsible), -99) FK_SalesRep,
ISNULL((SELECT PK_SalesOrigin
FROM VMDWAnalytical.DBO.DIM_SalesOrigin
WHERE OriginID = ST.SalesOriginID), -99) FK_SalesOrigin,
CASE
WHEN CIT.Qty < 0 AND RR.TransDate IS NULL THEN
-97
WHEN CIT.QTY >=0 AND RR.TransDate IS NULL THEN
-98
ELSE
ISNULL((SELECT PK_QualityCode
FROM VMDWAnalytical.dbo.DIM_QualityCode
WHERE QualityCode = RR.VMQualityCode), -99)
END FK_QualityCode,
CASE
WHEN CIT.Qty < 0 AND RR.TransDate IS NULL THEN
-97
WHEN CIT.QTY >=0 AND RR.TransDate IS NULL THEN
-98
ELSE
ISNULL((SELECT PK_QualityDetailCode
FROM VMDWAnalytical.dbo.DIM_QualityDetailCode
WHERE QualityDetailCode = SL.VMQualityDetailCode
AND QualityCode = RR.VMQualityCode), -99)
END FK_QualityDetailCode,
CASE
WHEN CIT.Qty < 0 AND RR.TransDate IS NULL THEN
-97
WHEN CIT.QTY >=0 AND RR.TransDate IS NULL THEN
-98
ELSE
ISNULL((SELECT PK_ResponsibilityCode
FROM VMDWAnalytical.dbo.DIM_ResponsibilityCode
WHERE ResponsibilityCode = RR.VMResponsibilityCode), -99)
END FK_ResponsibilityCode,
CASE
WHEN ST.CREATEDDATE <= DATEADD(YEAR, 2, (SELECT KPISTARTDATE FROM RDS_KPIInventTableRel WHERE ITEMID = IT.ITEMID)) THEN
(SELECT PK_NEWITEMFLAG FROM VMDWAnalytical.DBO.DIM_NewItemFlag WHERE NewItemFlag = 'NEW')
ELSE
(SELECT PK_NEWITEMFLAG FROM VMDWAnalytical.DBO.DIM_NewItemFlag WHERE NewItemFlag = 'EXISTING')
END FK_NewItemFlag,
ISNULL((SELECT T.TIMEKEY
FROM VMDWAnalytical.DBO.DIM_Time T
WHERE T.FullDate = RR.TransDate), 1) FK_TransDate,
ISNULL((SELECT T.TIMEKEY
FROM VMDWAnalytical.DBO.DIM_Time T
WHERE T.FullDate = RR.CreatedDate), 1) FK_CreatedDate,
ISNULL((SELECT T.TIMEKEY
FROM VMDWAnalytical.DBO.DIM_Time T
WHERE T.FullDate = RR.VMReceivedDate), 1) FK_VMReceivedDate,
CASE
WHEN CIT.Qty < 0 AND RR.TransDate IS NULL THEN
-97
WHEN CIT.QTY >=0 AND RR.TransDate IS NULL THEN
-98
ELSE
ISNULL((SELECT PK_ReturnAction
FROM VMDWAnalytical.dbo.DIM_ReturnAction
WHERE ReturnActionID = RR.ReturnActionID), -99)
END FK_ReturnAction,
CASE
WHEN CIT.Qty < 0 AND RR.TransDate IS NULL THEN
-97
WHEN CIT.QTY >=0 AND RR.TransDate IS NULL THEN
-98
ELSE
ISNULL((SELECT PK_StatusCode
FROM VMDWAnalytical.dbo.DIM_StatusCode
WHERE StatusCode = RR.VMStatusCode), -99)
END FK_StatusCode,
ISNULL(CIT.InvoiceID, 'zUnknown') InvoiceID,
ISNULL(CIT.InventTransId, 'zUnknown') InventTransId,
ISNULL(CIT.ItemId, 'zUnknown') ItemId,
ISNULL(ST.SalesID, 'zUnknown') SalesID,
ISNULL(RR.VMRaNumber, 'zUnknown') VMRaNumber,
CASE
--A, Take out the Service item, flag with -98
WHEN IT.ITEMGROUPID = 'SERVICE' THEN
-98
--B, There is an original SO and the difference between the dates is non-negative
WHEN (SELECT ST1.CREATEDDATE FROM RDS_SALESTABLE ST1 WHERE ST1.SALESID = ST.PURCHORDERFORMNUM) IS NOT NULL
AND DATEDIFF(DAY, (SELECT ST1.CREATEDDATE FROM RDS_SALESTABLE ST1 WHERE ST1.SALESID = ST.PURCHORDERFORMNUM), ST.CREATEDDATE) >= 0 THEN
DATEDIFF(DAY, (SELECT ST1.CREATEDDATE FROM RDS_SALESTABLE ST1 WHERE ST1.SALESID = ST.PURCHORDERFORMNUM), ST.CREATEDDATE)
--C, The last 10 characters of the refnum field start with SOR, and the orig SO date is not null and the difference between the dates is non-negative
WHEN RIGHT(ST.PURCHORDERFORMNUM, 10) LIKE 'SOR%' AND (SELECT ST1.CREATEDDATE FROM RDS_SALESTABLE ST1 WHERE ST1.SALESID = RIGHT(ST.PURCHORDERFORMNUM, 10)) IS NOT NULL
AND DATEDIFF(DAY, (SELECT ST1.CREATEDDATE FROM RDS_SALESTABLE ST1 WHERE ST1.SALESID = RIGHT(ST.PURCHORDERFORMNUM, 10)), ST.CREATEDDATE) >= 0 THEN
DATEDIFF(DAY, (SELECT ST1.CREATEDDATE FROM RDS_SALESTABLE ST1 WHERE ST1.SALESID = RIGHT(ST.PURCHORDERFORMNUM, 10)), ST.CREATEDDATE)
--D, There is an original SO and the difference between the dates is negative
WHEN (SELECT ST1.CREATEDDATE FROM RDS_SALESTABLE ST1 WHERE ST1.SALESID = ST.PURCHORDERFORMNUM) IS NOT NULL
AND DATEDIFF(DAY, (SELECT ST1.CREATEDDATE FROM RDS_SALESTABLE ST1 WHERE ST1.SALESID = ST.PURCHORDERFORMNUM), ST.CREATEDDATE) < 0 THEN
DATEDIFF(DAY, (SELECT SCT.CAMPAIGNDATE FROM RDS_SMMCAMPAIGNTABLE SCT WHERE SCT.CAMPAIGNID = ST.SMMCAMPAIGNID), ST.CREATEDDATE)
--E, The last 10 characters of the refnum field start with SOR, and the orig SO date is not null, and the difference between the dates is negative
WHEN RIGHT(ST.PURCHORDERFORMNUM, 10) LIKE 'SOR%' AND (SELECT ST1.CREATEDDATE FROM RDS_SALESTABLE ST1 WHERE ST1.SALESID = RIGHT(ST.PURCHORDERFORMNUM, 10)) IS NOT NULL
AND DATEDIFF(DAY, (SELECT ST1.CREATEDDATE FROM RDS_SALESTABLE ST1 WHERE ST1.SALESID = RIGHT(ST.PURCHORDERFORMNUM, 10)), ST.CREATEDDATE) < 0 THEN
DATEDIFF(DAY, (SELECT SCT.CAMPAIGNDATE FROM RDS_SMMCAMPAIGNTABLE SCT WHERE SCT.CAMPAIGNID = ST.SMMCAMPAIGNID), ST.CREATEDDATE)
--F, If the campaign date <> 1/1/1900 and the datediff is positive
WHEN (SELECT SCT.CAMPAIGNDATE FROM RDS_SMMCAMPAIGNTABLE SCT WHERE SCT.CAMPAIGNID = ST.SMMCAMPAIGNID) <> '1/1/1900'
AND DATEDIFF(DAY, (SELECT SCT.CAMPAIGNDATE FROM RDS_SMMCAMPAIGNTABLE SCT WHERE SCT.CAMPAIGNID = ST.SMMCAMPAIGNID), ST.CREATEDDATE) >= 0 THEN
DATEDIFF(DAY, (SELECT SCT.CAMPAIGNDATE FROM RDS_SMMCAMPAIGNTABLE SCT WHERE SCT.CAMPAIGNID = ST.SMMCAMPAIGNID), ST.CREATEDDATE)
--G, If the difference between the Return SO and the Return and Repair transdate is positive
WHEN DATEDIFF(DAY, ST.CREATEDDATE, RR.TRANSDATE) > 0 THEN
DATEDIFF(DAY, ST.CREATEDDATE, RR.TRANSDATE)
--H
ELSE
-97
END RETDAYS,
--RETURNS
-1 * (CASE
WHEN SL.SALESTYPE = 4 THEN
CIT.LINEAMOUNTMST
ELSE
0
END) AS ReturnLineAmount,
-1 * (CASE
WHEN SL.SALESTYPE = 4 THEN
CIT.QTY
ELSE
0
END) AS ReturnQty,
--/RETURNS
(CIT.LINEAMOUNTMST) AS LineAmountMst, --Measure
(CIT.QTY) AS Qty, --Measure
ISNULL(DATEDIFF(DAY, RR.CreatedDate, RR.TransDate), 0) ReturnDays,
ITMS.PRICE AS ListPrice --Measure
FROM RDS_CUSTINVOICETRANS CIT
LEFT JOIN RDS_CUSTINVOICEJOUR CIJ
ON CIT.INVOICEID = CIJ.INVOICEID
JOIN RDS_CUSTTABLE CT
ON CIJ.ORDERACCOUNT = CT.ACCOUNTNUM
LEFT JOIN RDS_ADDRESSCOUNTRYREGION ACR
ON CIJ.DLVCOUNTRYREGIONID = ACR.COUNTRYREGIONID
LEFT JOIN RDS_SALESTABLE ST
ON CIJ.SALESID = ST.SALESID
LEFT JOIN RDS_SALESLINE SL
ON CIT.INVENTTRANSID = SL.INVENTTRANSID
LEFT JOIN RDS_INVENTTABLE IT
ON CIT.ITEMID = IT.ITEMID
LEFT JOIN RDS_INVENTTABLEMODULE ITMS
ON IT.ITEMID = ITMS.ITEMID
AND ITMS.MODULETYPE = 2
LEFT JOIN RDS_VMRETURNANDREPAIRTABLE RR
ON SL.SALESID = RR.SALESID
AND SL.VMRANUMBER = RR.VMRANUMBER
LEFT JOIN RDS_INVENTDIM ID
ON SL.INVENTDIMID = ID.INVENTDIMID
) ABC
--WHERE SL.SALESTYPE = 4 --and (SELECT ST1.CREATEDDATE FROM RDS_SALESTABLE ST1 WHERE ST1.SALESID = ST.PURCHORDERFORMNUM) IS NULL
LEFT JOIN
(SELECT CIT.InventTransId AS InventTransId, CIT.ItemId AS ItemId, CIT.InvoiceId AS InvoiceId,
ISNULL((SELECT T.TIMEKEY
FROM VMDWANAlytical.DBO.DIM_Time T
WHERE T.FullDate = MAX(SR.ProdDate)),1) AS FK_InventSerialProdDate
FROM RDS_CustInvoiceTrans CIT
LEFT JOIN RDS_InventTrans IVT
ON CIT.InventTransId = IVT.InventTransId AND
CIT.InvoiceId = IVT.InvoiceId AND
CIT.ItemId = IVT.ItemId
LEFT JOIN RDS_INVENTDIM ID
ON IVT.InventDimId = ID.InventDimId
LEFT JOIN RDS_InventSerial SR
ON ID.InventSerialId = SR.InventSerialId AND
IVT.ItemId = SR.ItemId
GROUP BY CIT.InventTransId, CIT.ItemId, CIT.InvoiceId) ZZZ
ON ABC.InventTransId = ZZZ.InventTransId AND
ABC.ItemId = ZZZ.ItemId AND
ABC.InvoiceId = ZZZ.InvoiceId
I think you need to add an alias to the subquery so you'd have
SELECT * FROM ( MY QUERY HERE) as MyQuery