Combining rows on a query in access 2010 - ms-access

First off I know nothing about VB and the post I have seen on here refer to that, I am sure that this is a very simple thing to do so please help
I am trying to hve my TN Route be my primary key/no duplicates and have date driver 1 driver 2 and driver 3 all in diff cells and all side by side, and even though the tbl that it is pulling from the TN route is primary, it keeps adding additional rows for each driver.
See attached screenshot:
Thank you in advance.
Stan
data sheet view of query

This query will do it for you. Again, it's not preferable because in Access SQL tends to be a little messy on account of it not having features that more robust SQL platforms do - but it will work. You'll need to change the name of your Date column to Route Date in order for this to work, and replace my tblTest with whatever your table name is:
SELECT DISTINCT tblTest.[TN Route], tblTest.[Route Date], tA.[Driver 1], tB.[Driver 2], tC.[Driver 3]
FROM ((tblTest LEFT JOIN (SELECT tblTest.[TN Route], tblTest.[Route Date], [Driver 1] FROM tblTest WHERE [Driver 1] <> '') AS tA ON (tblTest.[Route Date] = tA.[Route Date]) AND (tblTest.[TN Route] = tA.[TN Route]))
LEFT JOIN (SELECT tblTest.[TN Route], tblTest.[Route Date], [Driver 2] FROM tblTest WHERE [Driver 2] <> '') AS tB ON (tblTest.[Route Date] = tB.[Route Date]) AND (tblTest.[TN Route] = tB.[TN Route]))
LEFT JOIN (SELECT tblTest.[TN Route], tblTest.[Route Date], [Driver 3] FROM tblTest WHERE [Driver 3] <> '') AS tC ON (tblTest.[Route Date] = tC.[Route Date]) AND (tblTest.[TN Route] = tC.[TN Route])
In Access 2010, go Create > Query Design > add your table, and then paste the SQL into the SQL view of the query designer. You can even make a standalone table out of the result.

Related

MSReport is showing 1 day behind for expiry date, compared to CRM?

Currently when I look at the expiry date section for insurance on my MSReport Builder it is 03/04/2017, but the expiry date section for my insurance in CRM is 04/04/2017 which is the correct and right, however in the report it is 1 day behind, therefore I was wondering why and what might be the fix to this? because I want it to show the same as CRM 04/04/2017, I've been researching and some articles said use UTC THE ONE THAT DONT START WITH 23 hours, not entirely sure how to put this in my query, I’m in the UK, and CRM options are for already set for UK as I checked it already. Again, please advise fix to this?
SELECT 'PAS ' +
SectionName AS SectionName,
SectionKey,
FormName,
ItemName,
ImportSequenceNumber,
ExpiryDate,
ExpiresOn,
#Param_MonthlyStatement_EntityRecordId AS AccountId
FROM
(SELECT
sect.mm_name AS SectionName,
sect.mm_key AS SectionKey,
frm.mm_name AS FormName,
frm.mm_name AS ItemName,
frm.mm_importsequencenumber AS ImportSequenceNumber,
MAX(frmans.mm_expires) AS ExpiryDate,
DATEADD(m, 2, GETDATE()) AS ExpiresOn
FROM Filteredmm_section AS sect INNER JOIN
mm_form AS frm ON sect.mm_sectionid = frm.mm_section INNER JOIN
mm_formanswer AS frmans ON frmans.mm_form = frm.mm_formId INNER JOIN
Account AS acc ON frmans.mm_AccountID = acc.AccountId
WHERE (sect.mm_name LIKE '%-%')
AND (sect.mm_parentsection IS NULL)
AND (CONVERT(NVARCHAR(250), frmans.mm_AccountID)
= #Param_MonthlyStatement_EntityRecordId)
AND ( acc.mm_supplier = 1)
GROUP BY sect.mm_name, sect.mm_key, frm.mm_name, frm.mm_importsequencenumber
HAVING (MAX(frmans.mm_expires) BETWEEN GETDATE() AND DATEADD(m, 2, GETDATE()))) AS t1
WHERE (NOT EXISTS (SELECT TOP (1) mm_accountid FROM Filteredmm_formanswer
WHERE (mm_formname = t1.FormName) AND (mm_accountid = #Param_MonthlyStatement_EntityRecordId) AND (mm_statusname = 'Awaiting Verification')))
ORDER BY SectionName, FormName, ImportSequenceNumber
You might want to get the expiry date from the filtered table, because I can see there is a filtering used, perhaps try
INNER JOIN Filteredmm_formanswer AS frmans ON frmans.mm_form = frm.mm_formId

SQL Subquery issue 3

I have a issue with my SQL code.
When I run this code I'm getting such error mesage:
**
Subquery returned more than 1 value. This is not permitted when the
subquery follows =, !=, <, <= , >, >= or when the subquery is used as
an expression.
**
I don't know how to correct this code to run it?
Can somebothy look at it and help me with it?
Thank you for your help,
SELECT dbo.FRA$.[GUID], dbo.FRA$.[Last Name],
dbo.FRA$.[First Name], dbo.FRA$.[HR Manager Last Name],
dbo.FRA$.[HR Manager First Name], (SELECT dbo.FRA$.[Business Email Address] FROM dbo.FRA$ t WHERE t.[HR Manager ID] = t.[Emplid]) AS [HR Manager E-Mail],
dbo.LOC.Descr AS [COMPANY NAME], dbo.FRA$.[Location Code],
dbo.LOC.[ADDRESS], dbo.LOC.Postal, dbo.LOC.City, dbo.FRA$.[National ID], dbo.FRA$.[Current Employee Class Desc] AS [Current Empl Class],
dbo.FRA$.[Contract type description] AS [CONTRACT TYPE], dbo.FRA$.[Business Title],
CASE dbo.FRA$.[Current Employee Class Desc]
WHEN 'Operator' THEN 10
WHEN 'Clerical worker' THEN 22
WHEN 'Technician' THEN 32
WHEN 'Supervisor' THEN 33
WHEN 'Manager&Engineer' THEN 54
END AS [Salary brutto],
FORMAT(dbo.FRA$.[Birthdate],'yyyy-MM-dd') AS [Birth Date], FORMAT(dbo.FRA$.[Last Start Date],'yyyy-MM-dd') AS [Hire Date]
FROM dbo.FRA$
INNER JOIN dbo.LOC
ON dbo.FRA$.[Location Code] = dbo.LOC.[Location]
WHERE [HR Status] IN ('International Assignment','Active','Leave of Absence');
Try to replace
SELECT dbo.FRA$.[Business Email Address] FROM dbo.FRA$ t WHERE t.[HR Manager ID] = t.[Emplid]
with
SELECT TOP 1 t.[Business Email Address] FROM dbo.FRA$ t WHERE [HR Manager ID] = t.[Emplid]
it will take only one row from rows returned by your subquery

Grouping by same column / variable using two separate imported views and separate calculations

So basically my code involves a created a table which has the LAST COLUMN as the SUM of the previous two columns, with the first of the two coming from table X and the second of the two columns coming from the 'INNER JOIN OF table X with table Y'.
HOWEVER, I want to group ALL THREE of these columns by the 'COUNTERPARTY', a variable which is present BOTH in 'table X' AND in 'INNER JOIN OF TABLE X WITH TABLE Y.'
The tricky part is that there will be some COUNTERPARTIES for which we have data set 1 (coming from TABLE X) and some COUNTERPARTIES for which we have data set 2 (coming from INNER JOIN OF table X with table Y) and SOME FOR WHICH WE HAVE BOTH DATASETS! I WANT TO INCLUDE THE INTERSECTION AS WELL AS THE OUTLIERS BUT ONLY AFTER CHECKED AGAINST A MASTER KEY OF COUNTERPARTIES called c.COUNTERPTY.
Please carefully go through the code below to see how the above explanation is relevant to the problem at hand. I apologize for the length of the code.
select
p.Name as ENTITY, t.[Counterparty Code], c.CNTRPTY_DS as COUNTERPARTY, cs.Tier,
... irrelevant code removed
sum((t.[Current value decimal] - t.[Trade price decimal])/100 * case when t.[Buy Sell Code] = 'B'
then 1 else -1 end * t.[Open Amount]) as [OPEN MTM ($)],
sum((t2.[Weighted Average Settled Pair Off Price] - t2.[Trade price decimal])/100 * case when t2.[Buy Sell Code] = 'B'
then 1 else -1 end * ISNULL(PO.[Pairoff Amount],0)) as [Unsettled Pairoffs/ AOTs ($)],
sum((t.[Current value decimal] - t.[Trade price decimal])/100 * case when t.[Buy Sell Code] = 'B'
then 1 else -1 end * t.[Open Amount]) + sum((t2.[Weighted Average Settled Pair Off Price] - t2.[Trade price decimal])/100 * case when t2.[Buy Sell Code] = 'B'
then 1 else -1 end * ISNULL(PO.[Pairoff Amount],0)) as [TOTAL MTM Exposure ($)]
from
[la-w08-qrm-db-1].qrmprod.dbo.vw_QRM_Trades t2
inner join
[la-w08-qrm-db-1].qrmprod.dbo.VW_QRM_TRADE_PAIROFFS PO
ON
PO.[In Ticket Number] = t2.[Ticket number]
and PO.[Portfolio ID] = t2.[Portfolio ID]
and t2.[derivative type] = 'F' -- note repeat below
and t2.[forward type] ='MBS'
and t2.[Counterparty Code] not in ('PLS', 'PNCO')
and t2.[Portfolio ID] in (1,7)
and t2.[Settlement date] > GETDATE(),
prod.dbo.vw_QRM_Trades t,
prod.dbo.portdesc p,
prod.dbo.cptyall c,
prod.dbo.VW_MB_ACTIVE_RUN r,
pulsar.dbo.CntrPrtySetup CS,
pulsar.dbo.CntrPrtyTiers CT
where
r.mrktid = 1
And r.asmpid = 1
And r.cyclid = 1
and r.compid = t.[Company ID]
and r.portid = t.[Portfolio ID]
and p.PORTID = t.[Portfolio ID]
and c.COUNTERPTY = t.[Counterparty Code] --key piece of code
and cs.CNTRPTY_NO = c.CNTRPTY_NO
and cs.PortID = t.[Portfolio ID]
and cs.Tier = ct.Tier
and t.[derivative type] = 'F' -- note repeat above
and t.[forward type] ='MBS'
and t.[Counterparty Code] not in ('PLS', 'PNCO')
and t.[Portfolio ID] in (1,7)
and t.[Open Amount] > 0
group by
p.Name, c.CNTRPTY_DS , t.[Counterparty Code], cs.Tier -- yes this
order by
p.Name, c.CNTRPTY_DS , t.[Counterparty Code], cs.Tier -- and this
The way to do is was to actually use UNION in order to join three tables together in the order and given the properties I wanted from each of them. Eventually I did manage to finish the whole stored procedure!

Access 2007 embedded Iif statement

Using Access 2007
My table has 9 columns. I have 4 columns I need to use to select a value based on dates in 3 other columns. In a nutshell, I need the most current cost to show in the last column (Current_Cost). I have tried several embedded Iif statements to no avail. I don’t know if I have been looking at this too long and I’m just not seeing my error or if I’m way off base.
Columns in table:
Item Number
Original Cost
Original Date
Cost 1
Date 1
Cost 2
Date 2
Cost 3
Date 3
UPDATE MyTable
SET Current_Cost =
IIf([MyTable]![DATE3]>[MyTable]![DATE 2],[MyTable]![COST 3],
IIf([MyTable]![DATE2]>[MyTable]![DATE 1],[MyTable]![COST 2],
IIf([MyTable]![DATE1]>[MyTable]![ORIGINAL DATE],[MyTable]![COST 1],
[MyTable]![ORIGINAL COST])));
FYI - I inherited this table so please don't bash me for the way it is set up!
I think Switch is easier to manage than a bunch of nested IIf expressions.
First try a SELECT query to work out the Switch logic. I think this is close to what you're aiming for:
SELECT
Switch
(
[DATE 3]>[DATE 2], [COST 3],
[DATE 2]>[DATE 1], [COST 2],
[DATE 1]>[ORIGINAL DATE], [COST 1],
True, [ORIGINAL COST]
) AS test_expression,
*
FROM MyTable;
After you have the correct Switch expression, you can use that in your UPDATE.
UDATE MyTable
SET Current_Cost =
Switch
(
[DATE 3]>[DATE 2], [COST 3],
[DATE 2]>[DATE 1], [COST 2],
[DATE 1]>[ORIGINAL DATE], [COST 1],
True, [ORIGINAL COST]
)
Interesting question, because of the multiple dates. First off: can you guarantee that the following statement always holds true for your table:
[ORIGINAL DATE] <= [DATE1] <= [DATE2] <= [DATE3]
If it does, your query will be a simple switch statement as per #HansUp's answer.* If it doesn't, then things become a little more interesting. My approach would be (and note that this will only work within the same Access database file as the query) to define a VBA function that takes two values and returns their maximum, let's call it Max2, then use this function to find the latest date for each row in the table, then pick the cost corresponding to that date:
update MyTable
set Current_Cost = switch(
DATE3 = Max2(Max2(Max2([ORIGINAL DATE], DATE1), DATE2), DATE3), [COST 3]
, DATE2 = Max2(Max2(Max2([ORIGINAL DATE], DATE1), DATE2), DATE3), [COST 2]
, DATE1 = Max2(Max2(Max2([ORIGINAL DATE], DATE1), DATE2), DATE3), [COST 1]
, true, [ORIGINAL COST]
)
The Max2 VBA function (can be defined in any module):
public sub Max2(v1 as variant, v2 as variant) as variant
if v1 < v2 then
Max2 = v2
else
Max2 = v1
end if
end sub
By the way, why Max2 and not just Max4? Reusability. You can use a function like this in many different places.
* You can check with a simple SQL query. You can also enforce this date order as a table check constraint in Access. Let me know if you need more info.
Let's evaluate what an IIF does:
IIF(SOME_CHECK,true_condition,false_condition)
Looking at your code, we see:
If
[MyTable]![DATE3]>[MyTable]![DATE 2]
then set Current_cost to be:
[MyTable]![COST 3]
Else go on to the next check..
If
[MyTable]![DATE2]>[MyTable]![DATE 1]
then set Current_cost to be:
[MyTable]![COST 2]
Else go on to the next check..
If
[MyTable]![DATE1]>[MyTable]![ORIGINAL DATE]
then set Current_cost to be:
[MyTable]![COST 1]
Else set to
[MyTable]![ORIGINAL COST]
So, is that what you are looking for?
If it is not, you may need to reverse your logic.. Instead of Cost 3, Cost 2, Cost 1 then change to Cost 1, Cost 2, and Cost 3..

Error creating a SP with temporal table inside and subquery

I've created this temporal table in my store procedure, as you can see I have more than 1 records for the same ID:
#tmpTableResults
TmpInstallerID TmpConfirmDate TmpConfirmLocalTime
============== ============== ===================
173 2011-11-08 11:45:50
278 2011-11-04 09:06:26
321 2011-11-08 13:21:35
321 2011-11-08 11:44:54
483 2011-11-08 11:32:00
483 2011-11-08 11:31:59
645 2011-11-04 10:03:15
645 2011-11-04 07:03:15
That is the result of the query to create #tmpTableResults
DECLARE #tmpTableResults TABLE
(
TmpInstallerID int,
TmpConfirmDate date,
TmpConfirmLocalTime time
)
DECLARE #tmpTableQuery VarChar(800)
SET #tmpTableQuery = 'select FxWorkorder.INSTALLERSYSID, FxWorkorder.CONFIRMDATE, FxWorkorder.CONFIRMLOCALTIME from FxWorkorder
join install on FxWorkorder.INSTALLERSYSID = install.sysid
join RouteGroupWorkarea on FxWorkorder.WORKAREAGROUPSYSID = RouteGroupWorkarea.IWORKAREA_ID
join RoutingGroup on RouteGroupWorkarea.IRG_ID = RoutingGroup.IRG_IDENTITY
where FxWorkorder.SCHEDULEDDATE > = #StartDate and FxWorkorder.SCHEDULEDDATE <= #EndDate
and FxWorkorder.Jobstatus <> "Unassign"
and FxWorkorder.Jobstatus <> "Route"
and install.FOXTELCODE <> ""
and FxWorkorder.CONFIRMLOCALTIME is not null
and FxWorkorder.CONFIRMDATE <> ""
group by FxWorkorder.INSTALLERSYSID, FxWorkorder.CONFIRMDATE, FxWorkorder.CONFIRMLOCALTIME
order by FxWorkorder.INSTALLERSYSID, FxWorkorder.CONFIRMDATE, FxWorkorder.CONFIRMLOCALTIME desc '
INSERT INTO #tmpTableResults EXEC(#tmpTableQuery)
I'm creating another query to get data from another table and only the first record from the temporal table for the same INSTALLERSYSID
SELECT RoutingGroup.SDESCRIPTION, FxWorkorder.INSTALLERSYSID, FxWorkOrder.JOBSTATUS, Install.FOXTELCODE,
install.NAME, FxWorkOrder.ScheduledDate,
count(*) as TotalJobs, COUNT(CONFIRMDATE) as ConfirmedJobs,
(select TmpInstallerID, TmpConfirmDate, TmpConfirmLocalTime from #tmpTableResults where TmpInstallerID = FxWorkorder.INSTALLERSYSID)
from FxWorkorder
join install on fxworkorder.INSTALLERSYSID = install.sysid
join RouteGroupWorkarea on FxWorkOrder.WORKAREAGROUPSYSID = RouteGroupWorkarea.IWORKAREA_ID
join RoutingGroup on RouteGroupWorkarea.IRG_ID = RoutingGroup.IRG_IDENTITY
where FxWorkorder.SCHEDULEDDATE > = #StartDate and FxWorkorder.SCHEDULEDDATE <= #EndDate
and FxWorkOrder.Jobstatus <> 'Unassign'
and FxWorkOrder.Jobstatus <> 'Route'
and Install.FOXTELCODE <> ''
group by RoutingGroup.SDESCRIPTION,FxWorkOrder.INSTALLERSYSID, FxWorkOrder.JOBSTATUS, Install.FOXTELCODE,install.NAME, FxWorkOrder.ScheduledDate,FxWorkOrder.WORKAREAGROUPSYSID
When I tried to save the sp I got the error
"Only one expression can be specified in the select list when the subquery is not introduced with EXISTS."
I can't see why I got this error. But if I run the query in sql that works. Can someone see the error?
I don't know how your second query works for you ‘in sql’ (where is that supposed to be? do you mean SSMS = SQL Server Management Studio?), but I'm sure it cannot possibly work in any version of SQL Server that exists at the moment. It's because of this subquery in the SELECT list:
(select TmpInstallerID, TmpConfirmDate, TmpConfirmLocalTime from #tmpTableResults where TmpInstallerID = FxWorkorder.INSTALLERSYSID)
The thing is, every expression in the SELECT clause should be scalar, but this subquery returns a row of more than one value. Even if it's only one row, it is illegal there, because it returns several columns. The subquery in that context should return no more than one value, i.e. it should be one column and the result produced should contain either no rows or just one.
You could try this query instead (although I'm not entirely sure without knowing more details about your schema):
SELECT
RoutingGroup.SDESCRIPTION,
FxWorkorder.INSTALLERSYSID,
FxWorkOrder.JOBSTATUS,
Install.FOXTELCODE,
install.NAME, FxWorkOrder.ScheduledDate,
count(*) as TotalJobs, COUNT(CONFIRMDATE) as ConfirmedJobs,
tmp.TmpInstallerID,
tmp.TmpConfirmDate,
tmp.TmpConfirmLocalTime
from FxWorkorder
join install on fxworkorder.INSTALLERSYSID = install.sysid
join RouteGroupWorkarea on FxWorkOrder.WORKAREAGROUPSYSID = RouteGroupWorkarea.IWORKAREA_ID
join RoutingGroup on RouteGroupWorkarea.IRG_ID = RoutingGroup.IRG_IDENTITY
join #tmpTableResults tmp ON tmp.TmpInstallerID = FxWorkorder.INSTALLERSYSID
where FxWorkorder.SCHEDULEDDATE > = #StartDate
and FxWorkorder.SCHEDULEDDATE <= #EndDate
and FxWorkOrder.Jobstatus <> 'Unassign'
and FxWorkOrder.Jobstatus <> 'Route'
and Install.FOXTELCODE <> ''
group by
RoutingGroup.SDESCRIPTION,
FxWorkOrder.INSTALLERSYSID,
FxWorkOrder.JOBSTATUS,
Install.FOXTELCODE,install.NAME,
FxWorkOrder.ScheduledDate,
FxWorkOrder.WORKAREAGROUPSYSID
tmp.TmpInstallerID,
tmp.TmpConfirmDate,
tmp.TmpConfirmLocalTime
That is, I added one more join, the one to #tmpTableResults, as well as added the columns you were trying to pull to the SELECT clause and to the GROUP BY clause.
Also, if I were you I would consider using short aliases for tables, like this:
SELECT
…
wo.INSTALLERSYSID,
wo.JOBSTATUS,
…
from FxWorkorder wo
join …
That might make your queries more readable.