Updating Table with multiple values - sql

When I run this code
UPDATE #YesterdayAssignments
SET ThisWeek = (
SELECT COUNT(*)
FROM #YesterdayAssignments U
INNER JOIN vstudyassignments A
ON U.HHID = A.lhouseholdid
INNER JOIN tstudies S
ON S.lstudyid = A.lstudyid
WHERE S.lstudytypeid IN (0,1,2)
AND S.bafteruse <> 1
AND S.lstatusid = 1
AND (A.dmailingdate BETWEEN DATEADD(DAY,1-DATEPART(dw,GETDATE()),GETDATE()) AND GETDATE()
OR A.dPulledDate BETWEEN DATEADD(DAY,1-DATEPART(dw,GETDATE()),GETDATE()) AND GETDATE())
AND S.dMailingDate < GETDATE()
GROUP BY HHID
)
FROM #YesterdayAssignments U
INNER JOIN vstudyassignments A
ON U.HHID = A.lhouseholdid
INNER JOIN tstudies S
ON S.lstudyid = A.lstudyid
WHERE S.lstudytypeid IN (0,1,2)
AND S.bafteruse <> 1
AND S.lstatusid = 1
AND (A.dmailingdate BETWEEN DATEADD(DAY,1-DATEPART(dw,GETDATE()),GETDATE()) AND GETDATE()
OR A.dPulledDate BETWEEN DATEADD(DAY,1-DATEPART(dw,GETDATE()),GETDATE()) AND GETDATE())
AND S.dMailingDate < GETDATE()
AND HHID = U.HHID
I get the error;
Msg 512, Level 16, State 1, Line 1
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
The statement has been terminated.
I need to update a table with multiple values. Any ideas?

I don't think the query is doing what you think. Try this (freehand):
WITH data (Total, HHID) AS
(
SELECT COUNT(*),
HHID
FROM #YesterdayAssignments U
INNER JOIN vstudyassignments A ON U.HHID = A.lhouseholdid
INNER JOIN tstudies S ON S.lstudyid = A.lstudyid
WHERE S.lstudytypeid IN (0,1,2)
AND S.bafteruse <> 1
AND S.lstatusid = 1
AND (A.dmailingdate BETWEEN DATEADD(DAY,1-DATEPART(dw,GETDATE()),GETDATE()) AND GETDATE()
OR A.dPulledDate BETWEEN DATEADD(DAY,1-DATEPART(dw,GETDATE()),GETDATE()) AND GETDATE())
AND S.dMailingDate < GETDATE()
GROUP BY HHID
)
UPDATE U
SET ThisWeek = Total
FROM #YesterdayAssignments U
INNER JOIN data D ON D.HHID = U.HHID;
The way you have it, you are grouping on HHID which potential returns multiple counts (when there is more than one HHID). So in effect, you are trying to do: ThisWeek = val1, val2, ..., valN.

Related

OLE DB or ODBC error: [DataSource.Error] Microsoft SQL: Subquery returned more than 1 value

My colleague who has left had mad a SQL query which don't want to run now because it keep saying that it returned more then 1 value.
The error is: OLE DB or ODBC error: [DataSource.Error] Microsoft SQL: Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression..
Can you guys help me out here what I need to adjust in the query to make it run?
WITH emp_orgs AS
(SELECT e.TT_EMP_ID,
soi.TT_ITEM AS Hoofdorganisatie
FROM tt_emp e
LEFT JOIN TT_VW_LABEL_EMP vle ON (e.TT_EMP_ID = vle.TT_DIM_ID)
LEFT JOIN TT_SYS_OPT_ITM soi ON (soi.TT_ITEM_ID = vle.TT_ITEM_ID)
AND soi.TT_OPT_ID = 5
AND soi.TT_CODE = 'TECH'),
raster_hours_next_6_months AS
(SELECT e.TT_EMP_ID,
(SELECT sum(si.TT_HOURS)
FROM TT_SYS_DAYS sd
LEFT JOIN TT_EMP_SCHED es ON (es.TT_EMP_ID = e.TT_EMP_ID --outer table
AND es.TT_FROMDATE <= sd.TT_DATE
AND es.TT_TODATE >= sd.TT_DATE)
LEFT JOIN TT_SCHEDDAY_ITM si ON (sd.TT_DATE = si.TT_DATE)
WHERE sd.TT_DATE >= getdate()
AND sd.TT_DATE <= DATEADD(MONTH, 6, getdate())
AND si.TT_SCHED_ID = es.TT_SCHED_ID ) AS raster_hours_next_6_months,
(SELECT 1 - isnull(ec.TT_PERCNOTPLAN, 0)/100 --percentage dat kan worden gepland
FROM TT_EMP_CONTRACT ec
WHERE ec.TT_EMP_ID = e.TT_EMP_ID
AND ec.TT_TODATE >= GETDATE() ) AS plannable_factor,
eo.Hoofdorganisatie
FROM TT_EMP e
LEFT JOIN emp_orgs eo ON eo.TT_EMP_ID = e.TT_EMP_ID
WHERE eo.Hoofdorganisatie IS NOT NULL )
SELECT soi.TT_ITEM_ID as CategoryKey,
(SELECT sum(r.raster_hours_next_6_months) / 6
FROM raster_hours_next_6_months r
WHERE r.Hoofdorganisatie = soi.TT_ITEM ) as ScheduledHours,
(SELECT sum(r.raster_hours_next_6_months * r.plannable_factor) / 6
FROM raster_hours_next_6_months r
WHERE r.Hoofdorganisatie = soi.TT_ITEM ) as ScheduledHoursPlannable
FROM TT_SYS_OPT_ITM soi
WHERE soi.TT_OPT_ID = 5
AND soi.TT_CODE = 'TECH'

Use if in where statement

I have 4 table:
Table_op_type
Table_maintenancetype
Table_repair_time
Table_repair_type
Each table has one column that can true or false and I have one Table_maintenancereport that has many columns and 4 columns in Table_maintenancereport foreign key given from 4 up table when I select Table_maintenancereport and one row in each table is true code working fine but when more than one row returned from table give this error.
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
How can I fix it?
My code is:
SELECT *
FROM Table_maintenancereport
WHERE mtypeid IN (IIF(#smtype = 1, (SELECT Table_maintenancetype.id FROM Table_maintenancetype WHERE enable_search = 1), mtypeid))
AND op_typeid IN (IIF(#sop IN (1), (SELECT Table_op_type.id FROM Table_op_type WHERE enable_search = 1), op_typeid))
AND repaire_timeid IN (IIF(#stime IN (1), (SELECT Table_repair_time.id FROM Table_repair_time WHERE enable_search = 1), repaire_timeid))
AND repaire_typeid IN (IIF(#stype = 1, (SELECT Table_repair_type.id FROM Table_repair_type WHERE enable_search = 1), repaire_typeid));
You need to fix the where conditions. You can do this with basic logic operators. Sets cannot be returned by iif() or by case() expressions.
So:
WHERE (#smtype <> 1 OR
mtypeid IN (SELECT Table_maintenancetype.id FROM Table_maintenancetype WHERE enable_search = 1)
) AND
(#sop <> 1 OR
op_typeid IN (SELECT Table_op_type.id FROM Table_op_type WHERE enable_search = 1)
) AND
(#stime <> 1 OR
repaire_timeid IN (SELECT Table_repair_time.id FROM Table_repair_time WHERE enable_search = 1)
) AND
(#stype <> 1 OR
repaire_typeid IN (SELECT Table_repair_type.id FROM Table_repair_type WHERE enable_search = 1)
);
If I am interpreting what you are trying to do correctly:
SELECT *
FROM Table_maintenancereport mr
LEFT OUTER JOIN Table_maintenancetype mt ON mr.mtypeid = mt.id AND enable_search = 1
LEFT OUTER JOIN Table_op_type ot ON mr.op_typeid = ot.id AND enable_search = 1
LEFT OUTER JOIN Table_repair_time rt ON mr.repaire_timeid = rt.id AND enable_search = 1
LEFT OUTER JOIN Table_repair_type rty ON mr.repaire_typeid = rty.id AND enable_search = 1
WHERE (ISNULL(#smtype,-1) != 1 OR mt.id IS NOT NULL)
AND (ISNULL(#sop,-1) != 1 OR ot.id IS NOT NULL)
AND (ISNULL(#stime,-1) != 1 OR rt.id IS NOT NULL)
AND (ISNULL(#stype,-1) != 1 OR rty.id IS NOT NULL)
so for each #variable, if it is set to 1, the corresponding field has to be one of the search enabled ids to appear in the output. If a variable is not set to 1, then it will not filter the corresponding field.
Maybe you can use CASE WHEN statement in where clause like:
select
*
from
Table_maintenancereport
where
case
when #smtype = 1 then mtypeid in (
select Table_maintenancetype.id
from
Table_maintenancetype
where
enable_search = 1)
else mtypeid = mtypeid end
....

create an classification for months ordered

I'm trying to create an column in my query to show an ordered classification ( show 1, 2, 3 ( as in first, second, third ...)) relative to date... in my current query i have filtered data from the last 12 months ( as example, from 1-9-2016 to 31-8-2017)
using DATEADD(mm; DATEDIFF(m; - 1; GETDATE()) - 12; 0)
for the first date and
DATEADD(s; - 1; DATEADD(mm; DATEDIFF(m; 0; GETDATE()) + 1; 0))
for the last day of the current month. And i also have two columns, one with the month and other with the year, both extracted from a document date column present in the data ( i'm using
MONTH(dbo.Mov_Venda_Cab.dtmData) and YEAR(dbo.Mov_Venda_Cab.dtmData)).
My goal is to have a column showing something like this :
If the month is the first from the interval ( if is month 9 and year 2016 ) is has to show 1 , if is the second ( month 10 and year 2016) , show 2, all continuously until the current month ( that is 8 and year 2017) and showing 12.
If the values where static i could do a simple case and would achieve what i wanted. My problem is that since when i get the data filtered by my current date and the 12 months behind, i don't manage to get the same result because i don't know exactly what i should do in the CASE expression.
so that it could help my columns are :
Item ; Qty ; Month ; Year ; dtmData ; orderedMonth
ORIGINAL QUERY :
SELECT DISTINCT DATEADD(mm, DATEDIFF(m, - 1, GETDATE()) - 12, 0) AS DATA_INI,
DATEADD(s, - 1, DATEADD(mm, DATEDIFF(m, 0, GETDATE()) + 1, 0)) AS DATA_FIM,
dbo.Mov_Venda_Lin.Id,
MONTH(dbo.Mov_Venda_Cab.dtmData) AS Mes,
YEAR(dbo.Mov_Venda_Cab.dtmData) AS Ano,
dbo.Mov_Venda_Lin.fltValorMercadoriaSIVA * dbo.Mov_Venda_Cab.intSinal AS Mercadoria,
dbo.Mov_Venda_Lin.fltValorLiquido * dbo.Mov_Venda_Cab.intSinal AS ValorLiquido,
CASE
WHEN tbl_tipos_documentos.bitconsideraqtdmapas = 1
THEN (Mov_Venda_Lin.fltQuantidade * mov_venda_cab.intsinal)
ELSE 0
END AS Quantidade,
dbo.Mov_Venda_Lin.strCodSeccao AS Seccao,
dbo.Mov_Venda_Lin.strAbrevTpDoc AS TpDoc,
dbo.Tbl_Tipos_Documentos.strDescricao AS DescTpDoc,
dbo.Mov_Venda_Lin.intNumLinha AS Linha,
dbo.Mov_Venda_Lin.strCodExercicio AS Exercicio,
dbo.Mov_Venda_Cab.strAbrevMoeda AS Moeda,
dbo.Mov_Venda_Cab.fltCambio AS Cambio,
dbo.Mov_Venda_Lin.strCodArtigo AS Artigo,
dbo.Tbl_Gce_Artigos.strDescricao AS DescArtigo,
dbo.Mov_Venda_Lin.strCodClassMovStk AS MovStk,
dbo.Tbl_ClassificacaoMovStk.strDescricao AS DescMovStk,
CASE
WHEN mov_venda_cab.inttpentidade = 0
THEN tbl_gce_tipos_entidade.strcodigo
ELSE NULL
END AS TpEntidade,
CASE
WHEN mov_venda_cab.inttpentidade = 0
THEN tbl_gce_tipos_entidade.strdescricao
ELSE NULL
END AS DescTpEntidade,
CASE
WHEN mov_venda_cab.intcodentidade <> 0
THEN mov_venda_cab.intcodentidade
ELSE NULL
END AS CodEntidade,
CASE
WHEN mov_venda_cab.inttpentidade = 0
AND mov_venda_cab.intcodentidade <> 0
THEN 'Cliente'
WHEN mov_venda_cab.inttpentidade = 1
AND mov_venda_cab.intcodentidade <> 0
THEN 'Outro Devedor'
ELSE NULL
END AS TipoEntidade,
CASE
WHEN mov_venda_cab.inttpentidade = 0
THEN tbl_clientes.strnome
ELSE tbl_outros_devedores.strnome
END AS DescNome,
dbo.Tbl_SubZonas.strAbrevZona AS Zona,
dbo.Tbl_Zonas.strDescricao AS DescZona,
dbo.Mov_Venda_Cab.strAbrevSubZona AS SubZona,
dbo.Tbl_SubZonas.strDescricao AS DescSubZona,
dbo.Mov_Venda_Cab.intCodVendedor AS Vendedor,
dbo.Tbl_Gce_Vendedores.strNome AS DescNomeVend,
dbo.Tbl_Gce_Artigos.strCodCategoria AS Categoria,
dbo.Tbl_Gce_Categorias.strDescricao AS DescCategoria,
dbo.Tbl_Gce_Artigos.strTpArtigo AS TpArtigo,
dbo.Tbl_Gce_Tipos_Artigos.strDescricao AS DescTpArtigo,
CAST(NULL AS VARCHAR(13)) AS CodFamiliaAgrup,
CAST(NULL AS VARCHAR(35)) AS DescFamAgrup,
CAST(NULL AS VARCHAR(13)) AS CodFamiliaRes,
CAST(NULL AS VARCHAR(35)) AS DescFamRes,
dbo.Mov_Venda_Cab.strForteAbrevMoeda AS abrevmoeda,
dbo.Mov_Venda_Cab.fltForteCambio AS fortecambio
FROM dbo.Mov_Venda_Lin WITH (NOLOCK)
LEFT OUTER JOIN dbo.Mov_Venda_Cab WITH (NOLOCK)
ON dbo.Mov_Venda_Lin.strCodSeccao = dbo.Mov_Venda_Cab.strCodSeccao
AND dbo.Mov_Venda_Lin.strAbrevTpDoc = dbo.Mov_Venda_Cab.strAbrevTpDoc
AND dbo.Mov_Venda_Lin.strCodExercicio = dbo.Mov_Venda_Cab.strCodExercicio
AND dbo.Mov_Venda_Lin.intNumero = dbo.Mov_Venda_Cab.intNumero
LEFT OUTER JOIN dbo.Tbl_Gce_Armazens WITH (NOLOCK)
ON dbo.Mov_Venda_Lin.strCodArmazem = dbo.Tbl_Gce_Armazens.strCodigo
LEFT OUTER JOIN dbo.Tbl_Gce_Artigos WITH (NOLOCK)
ON dbo.Tbl_Gce_Artigos.strCodigo = dbo.Mov_Venda_Lin.strCodArtigo
LEFT OUTER JOIN dbo.Tbl_Gce_ArtigosFamilias WITH (NOLOCK)
ON dbo.Tbl_Gce_Artigos.strCodigo = dbo.Tbl_Gce_ArtigosFamilias.strCodArtigo
LEFT OUTER JOIN dbo.Tbl_Gce_Familias WITH (NOLOCK)
ON dbo.Tbl_Gce_ArtigosFamilias.strCodFamilia = dbo.Tbl_Gce_Familias.strCodigo
LEFT OUTER JOIN dbo.Tbl_Gce_ArtigosReferencias WITH (NOLOCK)
ON dbo.Tbl_Gce_Artigos.strCodigo = dbo.Tbl_Gce_ArtigosReferencias.strCodArtigo
LEFT OUTER JOIN dbo.Tbl_Gce_Referencias WITH (NOLOCK)
ON dbo.Tbl_Gce_ArtigosReferencias.strCodReferencia = dbo.Tbl_Gce_Referencias.strCodigo
LEFT OUTER JOIN dbo.Tbl_Gce_Tipos_Artigos WITH (NOLOCK)
ON dbo.Tbl_Gce_Artigos.strTpArtigo = dbo.Tbl_Gce_Tipos_Artigos.strCodigo
LEFT OUTER JOIN dbo.Tbl_Clientes WITH (NOLOCK)
ON dbo.Mov_Venda_Cab.intCodEntidade = dbo.Tbl_Clientes.intCodigo
LEFT OUTER JOIN dbo.Tbl_Direccoes WITH (NOLOCK)
ON dbo.Mov_Venda_Cab.intCodEntidade = dbo.Tbl_Direccoes.intCodigo
AND dbo.Mov_Venda_Cab.intDireccao = dbo.Tbl_Direccoes.intNumero
AND dbo.Mov_Venda_Cab.intTpEntidade = dbo.Tbl_Direccoes.intTp_Entidade
LEFT OUTER JOIN dbo.Tbl_Outros_Devedores WITH (NOLOCK)
ON dbo.Mov_Venda_Cab.intCodEntidade = dbo.Tbl_Outros_Devedores.intCodigo
LEFT OUTER JOIN dbo.Tbl_Gce_Vendedores WITH (NOLOCK)
ON dbo.Mov_Venda_Cab.intCodVendedor = dbo.Tbl_Gce_Vendedores.intCodigo
LEFT OUTER JOIN dbo.Tbl_Tipos_Documentos WITH (NOLOCK)
ON dbo.Mov_Venda_Cab.strAbrevTpDoc = dbo.Tbl_Tipos_Documentos.strAbreviatura
LEFT OUTER JOIN dbo.Tbl_SubZonas WITH (NOLOCK)
ON dbo.Mov_Venda_Cab.strAbrevSubZona = dbo.Tbl_SubZonas.strAbreviatura
LEFT OUTER JOIN dbo.Tbl_Zonas WITH (NOLOCK)
ON dbo.Tbl_SubZonas.strAbrevZona = dbo.Tbl_Zonas.strAbreviatura
LEFT OUTER JOIN dbo.Tbl_Gce_Categorias WITH (NOLOCK)
ON dbo.Tbl_Gce_Artigos.strCodCategoria = dbo.Tbl_Gce_Categorias.strCodigo
LEFT OUTER JOIN dbo.Tbl_Gce_Seccoes WITH (NOLOCK)
ON dbo.Mov_Venda_Cab.strCodSeccao = dbo.Tbl_Gce_Seccoes.strCodigo
LEFT OUTER JOIN dbo.Tbl_Gce_Tipos_Entidade WITH (NOLOCK)
ON dbo.Tbl_Clientes.strTpEntidade = dbo.Tbl_Gce_Tipos_Entidade.strCodigo
LEFT OUTER JOIN dbo.Tbl_ClassificacaoMovStk WITH (NOLOCK)
ON dbo.Mov_Venda_Lin.strCodClassMovStk = dbo.Tbl_ClassificacaoMovStk.strCodigo
WHERE (dbo.Mov_Venda_Cab.intTpEntidade = 0
OR dbo.Mov_Venda_Cab.intTpEntidade IS NULL)
AND (dbo.Mov_Venda_Cab.strAbrevTpDoc IN ('CRFCX', 'FACIV', 'FACTC', 'FCTA', 'LANIV', 'LOFX', 'LONC', 'LXANI', 'NCFCX', 'NFACC', 'NFACE', 'NFACM', 'NFACT', 'NNCRC', 'NNCRE', 'NNCRM', 'NNDEB', 'NNDEC', 'NNDEV', 'NVDIC', 'NVDIN', 'XLACC', 'XLACD'))
AND (dbo.Mov_Venda_Cab.strCodSeccao IN ('1', 'ENCT1', 'ENCT2', 'ENCT3', 'ENCT4', 'ENCT5', 'ENCT6'))
AND (dbo.Mov_Venda_Cab.dtmData > DATEADD(mm, DATEDIFF(m, - 1, GETDATE()) - 12, 0))
AND (dbo.Mov_Venda_Cab.dtmData <= DATEADD(s, - 1, DATEADD(mm, DATEDIFF(m, 0, GETDATE()) + 1, 0)))
AND (dbo.Mov_Venda_Lin.intTpLinha > 2)
AND (dbo.Mov_Venda_Cab.bitAnulado = 0)
AND (dbo.Mov_Venda_Cab.bitConvertido = 0)
Luckily there's a much less complicated method than using a bunch of CASE statements. You can use the ROW_NUMBER function.
First, don't split your dates into month and year. Just use Getdate() to calculate your desired range and compare your source dates to that. Then you add the ROW_NUMBER to get your ordering output:
SELECT
*
,ordered_output = (ROW_NUMBER()OVER(PARTITION BY grouping_field ORDER BY cast(dtmData as datetime) ASC))
FROM Mov_Venda_Cab
WHERE cast(dtmData as datetime) >= getdate() - 365
This example assumes your have some ID field or similar on which your want to group your output, represented by grouping_field in the example. Your results would look like:
grouping_field dtmData ordered_output
1 8/1/2017 1
1 8/2/2017 2
1 8/3/2017 3
2 8/1/2017 1
2 8/2/2017 2
2 8/3/2017 3
If you don't want to group your output, just ordering everything by the date, you can omit the PARTITION BY grouping_field text. You'd get instead something like:
dtmData ordered_output
8/1/2017 1
8/2/2017 2
8/3/2017 3
8/4/2017 4
8/5/2017 5
8/6/2017 6
EDIT: Asker clarified that all records with the same month should get the same ordered output.
To do that you first need to assign each month/year combo a rank and rejoin that to the main table using two layers of subqueries:
SELECT b.*, c.month_rank
from Mov_Venda_Cab as b
inner join
(select mnt, yr, ROW_NUMBER() OVER(ORDER BY A.yr, A.mnt) AS month_rank
from (
SELECT DISTINCT
MONTH(dtmData) as mnt
, YEAR(dtmData) as yr
from Mov_Venda_Cab
WHERE cast(dtmData as datetime) >= getdate() - 365
) as a
) as c
on MONTH(b.dtmData) = c.mnt and YEAR(b.dtmData) = c.yr

Using subquery to find sum for individuals for reporting

I'm trying to calculate the sum of unposted transactions for individuals. I'm thinking I need a subquery to do this but I receive the
error (Msg 512, Level 16, State 1, Line 1
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.)
I should have known that I would get that error but I'm not sure how to tie in the table. Here's the full query:
select ar.id_num,
nm.last_name,
nm.first_name,
am.ADDR_LINE_1,
am.ADDR_LINE_2,
am.CITY,
am.STATE,
am.ZIP,
nm.EMAIL_ADDRESS,
ar.ar_bal_to_dte,
ar.UNAPPLIED_FIN_AID,
lt.Last_term_end_date
,ar.ar_bal_to_dte + ar.UNAPPLIED_FIN_AID as 'Unapplied Aid',
case when getdate()<= arm.end_dte then 'Dir Deposit' else 'Check' end as 'pmt type',
'Unposted Charges' = (select SUM (trans_amt) from TRANS_HIST where SOURCE_CDE = '#C' AND SUBSID_CDE = 'AR' group by ID_NUM )
from SUBSID_MASTER ar left outer join ccsc_last_term_end_date_v lt on ar.ID_NUM = lt.id_num
left outer join SUBSID_MASTER_EPAY_ACCT arm ON AR.ID_NUM = arm.ID_NUM
inner join TRANS_HIST th ON AR.ID_NUM = th.ID_NUM
JOIN NAME_MASTER nm ON ar.ID_NUM = nm.ID_NUM
JOIN ADDRESS_MASTER am on ar.ID_NUM = am.ID_NUM
where ar.SUBSID_CDE = 'AR'
and ar.AR_BAL_TO_DTE < 0 and am.ADDR_CDE = '*LHP'
order by lt.Last_term_end_date
Does anyone have some advice for me? It would be greatly appreciated.
This is the only subquery in the query:
'Unposted Charges' = (select SUM(trans_amt) from TRANS_HIST where SOURCE_CDE = '#C' AND SUBSID_CDE = 'AR' group by ID_NUM )
First, this looks really awkward. Only use single quotes for string and date constants. Use square braces:
[Unposted Charges] = (select SUM(trans_amt) from TRANS_HIST where SOURCE_CDE = '#C' AND SUBSID_CDE = 'AR' group by ID_NUM )
The problem is the GROUP BY. It returns a different row for each ID_NUM, hence the error.
One easy fix to the syntax problem is:
[Unposted Charges] = (select SUM(trans_amt) from TRANS_HIST where SOURCE_CDE = '#C' AND SUBSID_CDE = 'AR')
However, you probably intend:
[Unposted Charges] = (select SUM(th.trans_amt)
from TRANS_HIST th
where th.SOURCE_CDE = '#C' AND
th.SUBSID_CDE = 'AR' AND
th.ID_NUM = ar.ID_NUM
)
A nice alternative to the subselect would be to join to a derived table of
... INNER JOIN (SELECT TH.ID_NUM, SUM(TH.TRANS_AMT) AS UNPOSTED_CHARGES FROM TRANS_HIST TH WHERE TH.SOURCE_ID = '#C' AND TH.SUBSID_CDE = 'AR' GROUP BY TH.ID_NUM) DT ON DT.ID_NUM = AR.ID_NUM ...
So then you can just use DT.UNPOSTED_CHARGES in your select list.

SQL Server error: Subquery Returns more than 1 Value

I wrote a query, but I get this error:
Msg 512, Level 16, State 1, Line 1
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
This is my query:
SELECT
d.Description,
s.Version,
d.UtiPrefix,
d.UTI,
d.PrimaryAC,
s.ReportingObb,
s.ReportingObb,
d.LEI,
d.LEI_Countp,
d.LEI,
s.ReportingDeleg,
d.Curr,
c.Trade_Party_Domicile,
c.LEI_SGR,
Price = (
SELECT Price
FROM Price p
WHERE p.DATE = '2014-09-15 00:00:00.000'
)
FROM
Derivatives AS d
INNER JOIN
Settings AS s ON d.LEI_SGR = s.LEI_SGR
INNER JOIN
Clients c ON d.LEI_SGR = c.LEI_SGR
WHERE
c.LEI_SGR = '8156008BA0ABD6B3AE15'
As the error message tells you, your subquery returns more than one result. You can fix it like that:
For MySQL:
SELECT Price
FROM Price p
WHERE p.DATE = '2014-09-15 00:00:00.000'
LIMIT 1
For T-SQL:
SELECT TOP 1 Price
FROM Price p
WHERE p.DATE = '2014-09-15 00:00:00.000'
Hope this will help you
You need to force the subquery from returning more than one row.
One way is to use MAX():
...
Price = (
SELECT MAX(Price)
FROM Price p
WHERE p.DATE = '2014-09-15 00:00:00.000'
)
...
Other options:
AVG()
MIN()
TOP 1 / LIMIT 1 (etc depending on database)
This is because your subquery SELECT Price FROM Price p WHERE p.DATE = '2014-09-15 00:00:00.000' is returning more than one row. Your Price table has more than one price for 2014-09-15.
Updated: I see in a comment to another answer that you want to show ALL the prices for that date in the results. You will need to join the price table into your query. Not subquery the price table in your SELECT clause.
SELECT d.Description,
s.Version,
d.UtiPrefix,
d.UTI,
d.PrimaryAC,
s.ReportingObb,
s.ReportingObb,
d.LEI,
d.LEI_Countp,
d.LEI,
s.ReportingDeleg,
d.Curr,
c.Trade_Party_Domicile,
c.LEI_SGR,
p.Price
FROM Derivatives AS d
INNER JOIN Settings AS s
ON d.LEI_SGR = s.LEI_SGR
INNER JOIN Clients c
ON d.LEI_SGR = c.LEI_SGR
,price p
WHERE c.LEI_SGR = '8156008BA0ABD6B3AE15' and p.date = '2014-09-15 00:00:00.000'