Please help...
I'm trying to get traffic data from my site www.mentallica.co.il using SQL
The problem is that my left join query returns different value when I'm using two or more.
SELECT ISNULL(SUM([TrafficDay].UniqueTraffic), 0) AS TrafficDay,
[Topics].topicNumber
FROM [Topics]
LEFT JOIN [Traffic] AS TrafficDay
ON ([TrafficDay].Date >= '10/16/2013'
AND [TrafficDay].Date <= '10/16/2013')
AND [TrafficDay].TopicNumber = [Topics].TopicNumber
GROUP BY [Topics].TopicNumber
Will return a TrafficDay real value
And the problem query is
SELECT ISNULL(SUM([TrafficDay].UniqueTraffic), 0) AS TrafficDay,
ISNULL(SUM([TrafficWeek].UniqueTraffic), 0) AS TrafficWeek,
[Topics].topicNumber
FROM [Topics]
LEFT JOIN [Traffic] AS TrafficDay
ON ([TrafficDay].Date >= '10/16/2013'
AND [TrafficDay].Date <= '10/16/2013')
AND [TrafficDay].TopicNumber = [Topics].TopicNumber
LEFT JOIN [Traffic] AS TrafficWeek
ON ([TrafficWeek].Date > '10/09/2013'
AND [TrafficWeek].Date < '10/16/2013')
AND [TrafficWeek].TopicNumber = [Topics].TopicNumber
GROUP BY [Topics].TopicNumber
This will return different (much bigger) value for TrafficDay
Why is that ?
How can I get the real values for TrafficDay and TrafficWeek?
Any solution would be great!
How do i join the same table based on other table values...
Have you tried temporarily creating a new view by right clicking on any view and selecting 'New View' then copy and paste your query into the box below. From there you will have somewhat of an Access view of your query and may be able to better visualize and change your joins ie the arrows between tables. Just a suggestion. Works for me sometimes. Good luck.
Related
My title is probably not very clear, so I made a little schema to explain what I'm trying to achieve. The xxxx_uid labels are foreign keys linking two tables.
Goal: Retrieve a column from the grids table by giving a proj_uid value.
I'm not very good with SQL joins and I don't know how to build a single query that will achieve that.
Actually, I'm doing 3 queries to perform the operation:
1) This gives me a res_uid to work with:
select res_uid from results where results.proj_uid = VALUE order by res_uid asc limit 1"
2) This gives me a rec_uid to work with:
select rec_uid from receptor_results
inner join results on results.res_uid = receptor_results.res_uid
where receptor_results.res_uid = res_uid_VALUE order by rec_uid asc limit 1
3) Get the grid column I want from the grids table:
select grid_name from grids
inner join receptors on receptors.grid_uid = grids.grid_uid
where receptors.rec_uid = rec_uid_VALUE;
Is it possible to perform a single SQL that will give me the same results the 3 I'm actually doing ?
You're not limited to one JOIN in a query:
select grids.grid_name
from grids
inner join receptors
on receptors.grid_uid = grids.grid_uid
inner join receptor_results
on receptor_results.rec_uid = receptors.rec_uid
inner join results
on results.res_uid = receptor_results.res_uid
where results.proj_uid = VALUE;
select g.grid_name
from results r
join resceptor_results rr on r.res_uid = rr.res_uid
join receptors rec on rec.rec_uid = rr.rec_uid
join grids g on g.grid_uid = rec.grid_uid
where r.proj_uid = VALUE
a small note about names, typically in sql the table is named for a single item not the group. thus "result" not "results" and "receptor" not "receptors" etc. As you work with sql this will make sense and names like you have will seem strange. Also, one less character to type!
I have this code which is working fine except that I need to add one more condition:
SELECT record1.*,
tbl_mpsregion.maintenanceteam,
tbl_mpsregion.regionmps
INTO tbl_sapforecast
FROM tbl_mpsregion
RIGHT JOIN
(
SELECT sap_ip19.*,
dateserial(RIGHT(trim([SAP_IP19].[PlanDate]),4),mid(trim([SAP_IP19].[PlanDate]),4,2),LEFT(trim([SAP_IP19].[PlanDate]),2)) AS [DATE/FORECAST],
tbl_labourstandard.re,
tbl_labourstandard.manning,
tbl_labourstandard.skillset AS skillset,
tbl_regionmapping.maintenanceplant,
tbl_regionmapping.area,
tbl_regionmapping.region AS region,
tbl_regionmapping.onresponse,
[RE]*[Manning]/60 AS hours
FROM (sap_ip19
LEFT JOIN tbl_labourstandard
ON (
LEFT(sap_ip19.[Task list description],3) = tbl_labourstandard.jemenawc)
AND (
sap_ip19.[MntPlan] = cdbl(tbl_labourstandard.supplypoint )))
LEFT JOIN tbl_regionmapping
ON sap_ip19.location = cdbl([Tbl_RegionMapping].[FittersDistricts])) AS record1
ON (
record1.region = [Tbl_MPSRegion].[Region])
AND (
record1.skillset = [Tbl_MPSRegion].[Skillset]) ;
Criteria to add is: If SAP_IP19.MntPlan does not match Tbl_LabourStandard.SupplyPoint then use 0 for Tbl_LabourStandard.SupplyPoint. I am not using Server 2000 so using CASE is not a solution. Have tried IIF and SWITCH but they are not taking query to sleep mode (not evaluating). I read that JOINS with IIF or SWITCH cannot be used. Please help!
You should be able to add if's or switches but you could always handle this with an OR - it's not the most performance friendly but it should get the job done, example below:
LEFT JOIN tbl_labourstandard
ON
(LEFT(sap_ip19.[Task list description],3) = tbl_labourstandard.jemenawc)
AND
((Tbl_LabourStandard.SupplyPoint = SAP_IP19.MntPlan AND
sap_ip19.[MntPlan] = cdbl(tbl_labourstandard.supplypoint))
OR (sap_ip19.[MntPlan] = 0))
Someone gave me the following SQL and wants me to do a query using Access, so that it returns the information that they need. All dbo_**** are databases where they get the information from.
I tried to do the following SQL using a design view, but its not working, the datasheet(table) doesnt match the information.
I get lost in the lines LEFT OUTER JOIN ... I dont know what to do with anything after that. Can someone help me, please ?
Or if someone someone can edit the SQL so that it works on Access just copying in the SQL view mode.
Thank you.
Declare #data datetime
set #data = '2013-12-31'
--Fundos
SELECT
RelCliSFN.CdCrt,
MC5.Nome 'NomeCarteira',
MC5.CGC 'CNPJCarteira',
player_adm.NomeCurto 'Administrador',
RelCliSFN.Cliente,
CE5.Nome 'NomeCliente',
CE5.CPFCGC 'CPF/CNPJCliente',
VigRelCliSFN.DtIni,
VigRelCliSFN.DtFim
FROM
RelCliSFN
Inner JOIN MC5 ON MC5.Carteira = RelCliSFN.CdCrt
INNER JOIN MC5Auxiliar ON MC5.Carteira = MC5Auxiliar.Carteira
Inner Join VigRelCliSFN ON RelCliSFN.IdRelCliSFN = VigRelCliSFN.IdRelCliSFN
Inner Join CE5 ON CE5.Cliente=RelCliSFN.Cliente
LEFT OUTER JOIN PlayAdmxMC5 ON MC5.Carteira = PlayAdmxMC5.CdCrt AND PlayAdmxMC5.DtIniVig =
(SELECT MAX(DtIniVig) FROM PlayAdmxMC5 WHERE MC5.Carteira = CdCrt AND DtIniVig < MC5.DataAtual)
INNER JOIN Player player_adm ON PlayAdmxMC5.IdPlayAdm = player_adm.ID
WHERE
--MC5Auxiliar.bNaoExpCCSFN is null
((VigRelCliSFN.DtIni <= #data)
and ((VigRelCliSFN.DtFim >= #data) or (VigRelCliSFN.DtFim is null)))
and MC5.CGC <> 0
and CE5.Assessor not in (17, 99)
and CE5.CPFCGC <>0
and MC5.TipoCarteira <> 4
--and RelCliSFN.CdCrt = 3`
As the others already mentioned, your query has MS SQL-Server syntax. So there are three ways you could solve your problem.
Solution 1:
Create a view in the SQL-Server database.
To do this, open your SQL-Server Management Studio. Go to YourServer > databases > YourDatabase > views. Right click on "views" and then select "new view...". Close the "add table" window. Copy your sql-code into the sql window (the one saying "SELECT FROM"). You will get an error message saying that your code can't be displayed. Ignore it. Save your view. You can connect it to your Access database the same way you would connect a table.
Solution 2:
Use a SQL-Passthrough query in Access.
This is a bit complicated to explain, because almost every Access version has a slightly different menu. I'll explain it for Access 2007.
Create a new query. Close the "add table" window. Choose "Pass-Through" from the design menu (I don't know exactly if the menu label of the english version is "design". In my version it says "Entwurf"). Open the properties window. Insert the correct ODBC string. The easiest way to get an ODBC-string is to use one from an existing ODBC-table. Go to the VBA immediate window (Ctrl + G) and write ?CurrentDb.TableDefs("YourTable").Connect (instead of YourTable you have to insert the name of your ODBC-table). Press Return. You should get something like
ODBC;DSN=YourConnection;Description=IAmAnODBCConnection;APP=2007 Microsoft Office system;DATABASE=YourDatabase
Copy this string into the ODBC property of your query. Be sure the option "returns records" is set to "Yes". Copy you SQL into the query and save it.
Solution 3:
Convert your SQL Server syntax to Access syntax. Before doing this, you have to connect every table which is used in the query. I can't test my syntax conversion, but this should work:
PARAMETERS data DateTime = #2013-12-31#;
SELECT
RelCliSFN.CdCrt,
MC5.Nome "NomeCarteira",
MC5.CGC "CNPJCarteira",
player_adm.NomeCurto "Administrador",
RelCliSFN.Cliente,
CE5.Nome "NomeCliente",
CE5.CPFCGC "CPF/CNPJCliente",
VigRelCliSFN.DtIni,
VigRelCliSFN.DtFim
FROM
RelCliSFN
Inner JOIN MC5 ON MC5.Carteira = RelCliSFN.CdCrt
INNER JOIN MC5Auxiliar ON MC5.Carteira = MC5Auxiliar.Carteira
Inner Join VigRelCliSFN ON RelCliSFN.IdRelCliSFN = VigRelCliSFN.IdRelCliSFN
Inner Join CE5 ON CE5.Cliente=RelCliSFN.Cliente
LEFT OUTER JOIN PlayAdmxMC5 ON MC5.Carteira = PlayAdmxMC5.CdCrt AND PlayAdmxMC5.DtIniVig =
(SELECT MAX(DtIniVig) FROM PlayAdmxMC5 WHERE MC5.Carteira = CdCrt AND DtIniVig < MC5.DataAtual)
INNER JOIN Player player_adm ON PlayAdmxMC5.IdPlayAdm = player_adm.ID
WHERE
((VigRelCliSFN.DtIni <= [data])
and ((VigRelCliSFN.DtFim >= [data]) or (VigRelCliSFN.DtFim is null)))
and MC5.CGC <> 0
and CE5.Assessor not in (17, 99)
and CE5.CPFCGC <>0
and MC5.TipoCarteira <> 4
Well I don't know if Access can handle the equation of PlayAdmxMC5.DtIniVig = (Subquery). If it doesn't work, you should create a new query containing only the subquery and then connect it to this query.
MAIN CODE I am using
SELECT dbo_RelCliSFN.CdCrt, dbo_MC5.Nome AS NomeCarteira, dbo_MC5.CGC AS CNPJCarteira, dbo_RelCliSFN.Cliente, dbo_CE5.Nome AS NomeCliente, dbo_CE5.CPFCGC AS [CPF/CNPJCliente], dbo_VigRelCliSFN.DtIni, dbo_VigRelCliSFN.DtFim
FROM ((((dbo_RelCliSFN INNER JOIN dbo_CE5 ON dbo_RelCliSFN.Cliente = dbo_CE5.Cliente) INNER JOIN dbo_MC5 ON dbo_RelCliSFN.CdCrt = dbo_MC5.Carteira) INNER JOIN dbo_MC5Auxiliar ON dbo_MC5.Carteira = dbo_MC5Auxiliar.Carteira) INNER JOIN dbo_VigRelCliSFN ON dbo_RelCliSFN.IdRelCliSFN = dbo_VigRelCliSFN.IdRelCliSFN) LEFT JOIN Query1 ON dbo_MC5.Carteira = Query1.CdCrt
GROUP BY dbo_RelCliSFN.CdCrt, dbo_MC5.Nome, dbo_MC5.CGC, dbo_RelCliSFN.Cliente, dbo_CE5.Nome, dbo_CE5.CPFCGC, dbo_VigRelCliSFN.DtIni, dbo_VigRelCliSFN.DtFim, dbo_MC5.TipoCarteira, dbo_CE5.Assessor
HAVING (((dbo_RelCliSFN.CdCrt)=802) AND ((dbo_MC5.CGC)<>0) AND ((dbo_CE5.CPFCGC)<>0) AND ((dbo_VigRelCliSFN.DtIni)<=#12/31/2013#) AND ((dbo_VigRelCliSFN.DtFim)>=#12/31/2013# Or (dbo_VigRelCliSFN.DtFim) Is Null) AND ((dbo_MC5.TipoCarteira)<>4) AND ((dbo_CE5.Assessor) Not In (17.19)));
I have 3 tables,
SystemUsers
OrganisationalUnits
UserOrganisationUnits - Pivot with UserId/OrganisationUnitId foreign keys
All tables have an Active bit column and the OrganisationalUnit table has a CoveredTill datetime column.
I want a list of all UserOrganisationUnits where OrganisationalUnit "CoveredTill" is < x (value doesn't matter as will be set in clr) date and all tables records are active.
So far I've only managed to get unique users from my query so any advice would be much appreciated.
SELECT
SystemUsers.DisplayName, SystemUsers.Email,
OrganisationalUnits.Description, OrganisationalUnits.CoveredTill,
OrganisationalUnits.Id, OrganisationalUnits.ParentId, OrganisationalUnits.TypeId
FROM
SystemUsers
RIGHT OUTER JOIN
OrganisationalUnits ON SystemUsers.Id = OrganisationalUnits.Id
INNER JOIN
UserOrganisationUnits ON SystemUsers.Id = UserOrganisationUnits.Id
WHERE
(OrganisationalUnits.Active = 1)
AND (SystemUsers.Active = 1)
AND (UserOrganisationUnits.Active = 1)
AND (OrganisationalUnits.CoveredTill < '2017-03-31 00:00:00.000')
I randomly set the date as the above since I manually set the covered till date as "2015-03-31 00:00:00.000" on all OrganisationalUnits "CoveredTill" columns.
My aim is to have a single sql query string which I can use in my clr stored procedure to create a list of all users who need to be emailed because there organisational unit is no longer covered and for said email to include which organisational unit hence why just having a unique list of users isn't sufficient.
I already have the email code so it's just the query I'm having issues with.
Edit:-
I had first approached this as needing 3 separate queries which I guess after a bit more testing I'll have to revisit unless someone can spot what I'm doing wrong with the above query?
Edit 2:-
After working through the issue with sarin and preparing to provide him a sql db/query copy I found that some of the joins were pointing towards the wrong ID fields (automatically created from different panes so always be wary of anything they create) so below I've included the final solution. (Which includes a couple extra fields I decided might be useful).
SELECT OrganisationalUnits.Description, OrganisationalUnits.CoveredTill, SystemUsers.DisplayName, SystemUsers.Email,
UserOrganisationUnits.LastVisited AS UOULastVisited, SystemUsers.LastVisited AS SULastVisited
FROM UserOrganisationUnits INNER JOIN
OrganisationalUnits ON UserOrganisationUnits.OrganisationUnitId = OrganisationalUnits.Id INNER JOIN
SystemUsers ON UserOrganisationUnits.UserId = SystemUsers.Id
WHERE (OrganisationalUnits.Active = 1) AND (SystemUsers.Active = 1) AND (UserOrganisationUnits.Active = 1) AND
(OrganisationalUnits.CoveredTill < '2017-03-31 00:00:00.000')
Performing a Right\left join before you do an inner join can give you unexpected results as it may produce nulls and your inner join will then attempt to filter them out. I'm not entirely clear about the relationships between the tables but can you turn them all into INNER JOINS to get the same list and produce you a similar result based on your expected outcome?
"My aim is.... to create a list of all users who need to be emailed because there organisational unit is no longer covered"
UPDATED:
SELECT
SystemUsers.DisplayName, SystemUsers.Email,
OrganisationalUnits.Description, OrganisationalUnits.CoveredTill,
OrganisationalUnits.Id, OrganisationalUnits.ParentId, OrganisationalUnits.TypeId
FROM
UserOrganisationUnits
INNER JOIN SystemUsers ON SystemUsers.Id = UserOrganisationUnits.Id
AND (SystemUsers.Active = 1)
INNER JOIN OrganisationalUnits ON OrganisationalUnits.Id = SystemUsers.Id
AND OrganisationalUnits.Active = 1
AND OrganisationalUnits.CoveredTill < '2017-03-31 00:00:00.000'
WHERE UserOrganisationUnits.Active = 1
I am trying to build some parametrized data source (sql query over jndi).
query of my data source is:
SELECT ${param_interval}(dim_date.date), count(docs_fact.id) as docs_count
FROM rel_docs_dates
left join docs_fact on rel_docs_dates.doc_id = docs_fact.id
left join dim_date on rel_docs_dates.date_id = dim_date.id
Parametr ${param_interval} can get two values: MONTH and DAY, and as i checked it got the correct values.
But when i am trying to make preview of my dashboard i get warning "error processing component".
Notice that this query (see bellow) works ok.
SELECT MONTH(dim_date.date), count(docs_fact.id) as docs_count, ${param_interval} as tmp_fiel
FROM rel_docs_dates
left join docs_fact on rel_docs_dates.doc_id = docs_fact.id
left join dim_date on rel_docs_dates.date_id = dim_date.id
Can somebody tell me where is mistake? Or (may be) this way to use parameters in data source is not supported?
finaly i found decision. it isnt what i would like to have but it works and it the most important thing.
i rewrite my query with 'case' constraction and, it is important, i changed type of my parametr from string to numeric (string doesnt work :( ). now my query looks like this:
SELECT
case ${param_interval}
when 1 then MONTH(dim_date.date)
when 2 then DAY(dim_date.date)
end
,count(docs_fact.id) as fact_count
FROM rel_docs_dates
left join docs_fact on rel_docs_dates.doc_id = docs_fact.id
left join dim_date on rel_docs_dates.date_id = dim_date.id
where dim_date.date > LAST_DAY(DATE_SUB(CURDATE(), INTERVAL ${param_period} MONTH))
AND dim_date.date < LAST_DAY(DATE_SUB(CURDATE(), INTERVAL 0 MONTH))
group by
case ${param_interval}
when 1 then MONTH(dim_date.date)
when 2 then DAY(dim_date.date)
end
order by YEAR(dim_date.date), MONTH(dim_date.date)
may be it will help somebody else.