I have a query which gets all public transport subscriptions. A subscription can have multiple related companies. So I wanted to do with my query is to get all the subscriptions and instead of creating a row each time I have a related company, the companies should by group into one column. Is it possible to do that?
Here's the query :
SELECT pts.Id_PublicTransportSubscription,
pts.Amount,
ptc.Name
FROM bm_PublicTransportSubscriptions AS pts
INNER JOIN bm_PublicTransportSubscriptionByCompany AS ptsbc
ON pts.Id_PublicTransportSubscription = ptsbc.Id_PublicTransportSubscription
INNER JOIN bm_PublicTransportCompanies AS ptc
ON ptsbc.Id_PublicTransportCompany = ptc.Id_PublicTransportCompany
I'm using SQL Server 2008.
You can use the GROUP_CONCAT aggregate function.
Related
This may have been mentioned here before, but I couldn't find an answer to the exact problem I'm trying to solve.
I am using SSMS 2018 v18.8 with SQL Server 2012 SP4.
My query requires querying multiple tables with joins.
One table (table 2) contains multiple values, and I'd like to return them in the query as a concatenated line.
How should I write my query to return the desired output?
Normally, you want the client application or reporting tool to roll up data like this. However, in Sql Server 2017 and later you can use the string_agg() function (along with GROUP BY) to make this happen.
SELECT t1.System, t1.Location, string_agg(t2.User, ',') As [User]
FROM Table1 t1
INNER JOIN Table2 t2 ON t1.System=t2.System
GROUP BY t1.System, t1.Location
Earlier versions need an ugly FOR XML PATH query.
Very simple answer using US States and Counties, Counties table contains a key (StateID) identifying the State the County belongs to.
SELECT States.name, STRING_AGG(CONVERT(NVARCHAR(max), ISNULL(County,'N/A')), ', ') AS Counties
FROM Counties
join States on Counties.StateID=State.ID
GROUP BY States.name;
I am trying to write a query that should perform join (or where clause) using the following criteria:
Subquery of left table should contain results of subquery from the right table (results also should be grouped).
sql script creating tables with data
Exact criteria is the following:
Select clients who:
For each Question.Id in [ClientSegment]'s questionIds
Should be at least one (equivalent on Any in LINQ) ClientAnswers.AnswerId from those in [ClientSegmentAnswers]
How I can achieve that without using for loops (cursors) in a single query?
UPD
Added script for creating tables and data
Expected result
Query that selects Bob as only matching consumers for ClientSegment with id = 1;
SQL JOINS will help for achieve this in single query,
E.g :
select
c.name,
c.id,
...
from Question as que
left join ClientSegment as cs on que.id=cs.id
left join ClientSegmentAnswers as csans on csans.ClientSegmentID=cs.id
left join Answer as ans on ans.id=csans.answerid
left join ClientAnswer as ca on ca.answerid=ans.answerid
left join Client as c on c.id=ca.ClientID
where ca.ClientID is not null
This query will return only clientname who are answering atleast one question also you can modify the query for your need.
I would like to JOIN 2 databases.
1 database is keyword_data (keyword mapping)
1 database is filled with Google rankings and other metrics
Somehow I cannot JOIN these two databases.
Some context:
DATA SET NAME: visibility
TABLE 1
keyword_data
VALUES
keyword
universe
category
search_volume
cpc
DATA SET NAME: visibility
TABLE 2
results
VALUES
Date
Keyword
Website
Position
In order to receive ranking data by date I wrote the following SQL line.
SELECT Date, Position, Website FROM `visibility.results` Keyword INNER
JOIN `visibility.keyword_data` keyword ON `visibility.results` Keyword
= `visibility.keyword_data` keyword GROUP BY Date;
(besides that, 100 other lines with no success ;-) )
I am using Google BigQuery for this with standard SQL (unchecked Legacy SQL).
How can I JOIN those 2 data tables?
How familiar are you with SQL? I think you're using aliases wrong, something like this should work
SELECT r.Date, r.Position, r.Website
FROM `visibility.results` AS r
INNER JOIN `visibility.keyword_data` AS k
ON r.Keyword = k.keyword
GROUP BY DATE
First of all i have never worked with Google big query but there is a couple of things wrong in my opinion with this query.
To start with you join tables by including the name of the table then you provide the key that the tables are joined by. Also if you don't use aggregate functions (MIN/MAX etc.) in your select statement you must include all values in the group by clause as well. In reference I can provide you a solution that would work if you would of used Microsoft SQL Server if that would be of any help because if you reference here the syntax is quite similar.
SELECT results.Date AS DATE,
,results.Position AS POSITION
,results.Website AS WEBSITE
FROM visibility.dbo.keyword_data AS keyword_data
INNER JOIN visibility.dbo.results AS results
ON results.keyword = keyword_data.keyword
GROUP BY results.Date
,results.Position
,results.Website
I am trying to convert a T-SQL query to MS Access SQL and getting a syntax error that I am struggling to find. My MS Access SQL query looks like this:
INSERT INTO IndvRFM_PreSort (CustNum, IndvID, IndvRScore, IndRecency, IndvFreq, IndvMonVal )
SELECT
IndvMast.CustNum, IndvMast.IndvID, IndvMast.IndvRScore,
IndvMast.IndRecency, IndvMast.IndvFreq, IndvMast.IndvMonVal
FROM
IndvMast
INNER JOIN
OHdrMast ON IndvMast.IndvID = OHdrMast.IndvID
INNER JOIN
MyParameterSettings on 1=1].ProdClass
INNER JOIN
[SalesTerritoryFilter_Check all that apply] ON IndvMast.SalesTerr = [SalesTerritoryFilter_Check all that apply].SalesTerr
WHERE
(((OHdrMast.OrdDate) >= [MyParameterSettings].[RFM_StartDate]))
GROUP BY
IndvMast.CustNum, IndvMast.IndvID, IndvMast.IndvRScore,
IndvMast.IndRecency, IndvMast.IndvFreq, IndvMast.IndvMonVal,
[CustTypeFilter_Check all that apply].IncludeInRFM,
[ProductClassFilter_Check all that apply].IncludeInRFM,
[SourceCodeFilter_Check all that apply].IncludeInRFM,
IndvMast.FlgDontUse
I have reviewed differences between MS Access SQL and T-SQL at http://rogersaccessblog.blogspot.com/2013/05/what-are-differences-between-access-sql.html and a few other locations but with no luck.
All help is appreciated.
update: I have removed many lines trying to find the syntax error and I am still getting the same error when running just (which runs fine using T-SQL):
SELECT
IndvMast.CustNum, IndvMast.IndvID, IndvMast.IndvRScore,
IndvMast.IndRecency, IndvMast.IndvFreq, IndvMast.IndvMonVal
FROM
IndvMast
INNER JOIN
OHdrMast ON IndvMast.IndvID = OHdrMast.IndvID
INNER JOIN
[My Parameter Settings] ON 1 = 1
There are a number of items in your query that should also have failed in any SQL-compliant database:
You have fields from tables in GROUP BY not referenced in FROM or JOIN clauses.
Number of fields in SELECT query do not match number of fields in INSERT INTO clause.
The MyParameterSettings table is not properly joined with valid ON expression.
Strictly MS Access SQL items:
For more than one join, MS Access SQL requires paired parentheses but even this can get tricky if some tables are joined together and their paired result joins to outer where you get nested joins.
Expressions like ON 1=1 must be used in WHERE clause and for cross join tables as MyParameterSettings appears to be, use comma-separated tables.
For above reasons and more, it is advised for beginners to this SQL dialect to use the Query Design builder providing table diagrams and links (if you have the MS Access GUI .exe of course). Then, once all tables connect graphically with at least one field selected, jump into SQL view for any nuanced scripting logic.
Below is an adjustment to SQL statement to demonstrate the parentheses pairings and for best practices, uses table aliases especially with long table names.
INSERT INTO IndvRFM_PreSort (CustNum, IndvID, IndvRScore, IndRecency, IndvFreq, IndvMonVal)
SELECT
i.CustNum, i.IndvID, i.IndvRScore, i.IndRecency, i.IndvFreq, i.IndvMonVal
FROM
[MyParameterSettings] p, (IndvMast i
INNER JOIN
OHdrMast o ON i.IndvID = o.IndvID)
INNER JOIN
[SalesTerritoryFilter_Check all that apply] s ON i.SalesTerr = s.SalesTerr
WHERE
(o.OrdDate >= p.[RFM_StartDate])
GROUP BY
i.CustNum, i.IndvID, i.IndvRScore, i.IndRecency, i.IndvFreq, i.IndvMonVal
And in your smaller SQL subset, the last table does not need an ON 1=1 condition and may be redundant as well in SQL Server. Simply a comma separate table will suffice if you intend for cross join. The same is done in above example:
SELECT
IndvMast.CustNum, IndvMast.IndvID, IndvMast.IndvRScore,
IndvMast.IndRecency, IndvMast.IndvFreq, IndvMast.IndvMonVal
FROM
[My Parameter Settings], IndvMast
INNER JOIN
OHdrMast ON IndvMast.IndvID = OHdrMast.IndvID
I suppose there are some errors in your query, the first (more important).
Why do you use HAVING clause to add these conditions?
HAVING (((IndvMast.IndRecency)>(date()-7200))
AND (([CustTypeFilter_Check all that apply].IncludeInRFM)=1)
AND (([ProductClassFilter_Check all that apply].IncludeInRFM)=1)
AND (([SourceCodeFilter_Check all that apply].IncludeInRFM)=1)
AND ((IndvMast.FlgDontUse) Is Null))
HAVING usually used about conditions on aggregate functions (COUNT, SUM, MAX, MIN, AVG), for scalar value you must put in WHERE clause.
The second: You have 12 parenthesis opened and 11 closed in HAVING clause
I'm developing an IT Support Management database. The following SQL query involves two tables. The 'devices' table contains all the PCs owned by a company, and the 'services' table is a list of every service performed on devices (ie. each device can have multiple services).
I want this query to retrieve the entire 'devices' table, but include an extra column that shows the total number of services for each device.
The following statement I've come up with is probably far from correct. For every row, it returns a count of the total number of records in the 'services' table (ie. same number on each row) rather than grouping/filtering to each device.
SELECT *,
(SELECT Count(services.id)
FROM dbo.services
LEFT JOIN devices
ON services.assetID = devices.assetID
GROUP BY devices.assetID) AS TotalServices
FROM dbo.devices
What approach should I be using to achieve this? Thanks in advance for any guidance or assistance!
If you want all the rows from devices table then dbo.devices should be present in left side of Left outer Join.
Remove the subquery and make it as Left outer join then count the number of service per assetID. Try this.
SELECT devices.assetID,
TotalServices=Count(services.id)
FROM dbo.devices
LEFT JOIN dbo.services
ON services.assetID = devices.assetID
GROUP BY devices.assetID