SQL Server pulling data from multiple tables - sql-server

I'm having a problem trying to pull a specific data from two tables. According to the textbook its:
Select *
From terra..retailsales and terra..retailaccount
Where retailaccountid in retailsales = 2345678
Get date range from = 3/01/2014 to 6/30/2015
However, when running the code it produces an syntax error within the in. Yet to me the whole code looks wrong. Can someone help me. I would like to get this to work in order to do my assignment. It's driving me nuts! I contacted the prof and he said that the code in the book is correct, but I think he's wrong.
Can someone help?

The code you provided is not TSQL - actually looks more like some kind of pseudocode.
Just guessing at your column names here, but if I've got it right your query should look something like this:-
SELECT * FROM terra..retailsales
WHERE retailaccountid = 2345678
AND [date range] BETWEEN '20140301' AND '20150630'
Not sure where the 2nd table comes into this though.

You can JOIN two table, like this:
SELECT *
FROM terra..retailsales RS
INNER JOIN terra..retailaccount RC
ON RS.retailaccountid = RC.ID
WHERE RS.retailaccountid = 2345678
AND [date] BETWEEN '20140301' AND '20150630'

Your provided code is very confusing. I see the [terra..retailsales] table, but have no idea what your other table is. Are you sure you need to get your data from two tables?
What is the syntax error you're receiving? Can you paste the exact code you're trying in a code block? Not much of that makes any sense.
In order to pull data from two tables, you could union those tables in a CTE (common table expression), throw them both into a temp table, or join them in a select statement. If the format of both tables is identical, then why do you have two of them?
You're missing the column name where you want to compare a [date] to "3/01/2014 to 6/30/2015". You can use getDate() to return the current time.
Select *
FROM [terra..retailsales]
Where [retailaccountid] = 2345678
AND [<DateColumn>] BETWEEN '3/01/2014' AND '6/30/2015'
You don't need to re-specify your table name again in line "Where retailaccountid in retailsales = 2345678". It will just assume that the retailaccountid is from retailsales.

Related

SQL group searching and matching between two tables

Working on a physical security migration. Have two tables. First table (AreaAccess) lists the badgeholder with the areaid's the badgeholder has access to. Second table (AreaGroups) has areaid's grouped together in sets. The goal is to read the cardholder's AreaAccess records and then search the AreaGroups for the count of the best or exact match of the cardholder's areas to a group.
Curious why you didn't give this a shot first. If you aren't as familiar with SQL, here's a great link to get started: https://www.w3schools.com/sql/
Also, it's extremely helpful if you can provide a sample of what you want the outcome to look like. It doesn't have to be fancy, just a few rows/columns that can demonstrate what you're hoping to see.
Here's a possible look. However, your question is a little vague, so this is a best guess.
create table ##CardToArea --Is this table a log, or is it grouping of permission? I'm treating it as a log, but the wording of your question isn't quite clear.
(
CardholderID int not null
, AreaID int not null
);
insert into ##CardToArea
(CardholderID,AreaID)
values
(1961,11)
,(1961,25)
,(1961,28)
,(1961,71)
,(1961,73)
,(1961,74)
,(1961,44)
,(1961,50)
,(1961,51)
,(1961,52);
create table ##AreaToGroup
(
AreaID int not null
, AreaGroupID int not null
, unique (AreaID,AreaGroupID)
);
insert into ##AreaToGroup
(AreaID,AreaGroupID)
values
(33,0)
,(45,0)
,(45,7)
,(19,16)
,(17,16)
,(11,16)
,(11,48)
,(17,48)
,(17,49)
,(15,49)
,(11,49);
select
isnull(convert(nvarchar,atg.AreaGroupID),'Not defined') as [AreaGroupID]
, cta.CardholderID
, count(*) as [CountOfAccesses]
from ##CardToArea as cta
left join ##AreaToGroup as atg on cta.AreaID = atg.AreaID
group by
atg.AreaGroupID
, cta.CardholderID;
drop table ##AreaToGroup;
drop table ##CardToArea;
#Robert - thanks for the response.
This is my query I had worked through yesterday. Looking only at two sample users (23006 and 28190). The result is a full report of the areasets these users are part of. What I have been trying to do, hence yesterdays question, is to limit the query to the top five areacounts for each cardholder. Attempted to use ROW_NUMBER processing but that was not working primarily because of the alias for "count(g.areaid)" in the select. I also tried numerous sub queries but to no avail.
select g.AreaGroupID, ag.caption, count(g.areaid) as AreaCount, a.CardholderID
from AHBadgeActivity B
join areaaccess a on a.CardholderID=b.CardholderID
left join AreaGroupSet g
on g.areaid=a.AreaID
left join AreaGroup ag on AG.AreaGroupID=g.AreaGroupID
where (a.CardholderID=23006 or a.CardholderID=28190) and DeleteFlag=0 and g.AreaGroupID <> 0
group by g.AreaGroupID, ag.Caption, a.CardholderID
order by a.cardholderid, AreaCount desc
Here is the sample output. My goal is to limit to the top five AreaCounts for each Cardholder.
Output from Query

Query table 1 (sales data) using criteria in table 2 (definitions) - WHEN NO COMMON FIELDS

I need to create an interactive tool in SSRS or Access where users enter definitions of promotions, then system delivers sales data relevant to those criteria.
User will choose which promotion to report and system should use associated promo definitions to deliver results.
I tried using a prompt to select promotion, then inserting the prompted value in a subquery in Access, but it doesn't like my syntax. It looked like:
SELECT R.NumberPresented
FROM dbo_MKT_PromoRecapMetric R
WHERE R.DonationDate =
(Select P.5007Start
FROM [Promo Definitions] P
WHERE P.PromoName = [Forms]![Promo.Select]![Promo]
AND R.LocationCode = '5007')
I've been working on this for a LONG time, and any help would be much appreciated...
UPDATE: Thanks for the table join solution. I should have mentioned in my post that the date criteria is simplified. I actually will need to pick up a start and end date for the promotion to drive the date range for the query. I don't think I'd be able to do that with a join.
I think I'm looking for an equivalent of an Excel lookup in sql.
Thanks.
Instead of using a subquery for your where statement, try joining your tables instead.
SELECT R.NumberPresented
FROM dbo_MKT_PromoRecapMetric AS R
INNER JOIN [Promo Definitions] AS P
ON P.[5007Start] = R.DonationDate
WHERE (((P.PromoName)=[forms]![Promo.Select]![Promo])
AND ((R.LocationCode)="5007"));

SQL Server - Count the number of times the contents of a specified field repeat in a table

What's the best way to 'SELECT' a 'DISTINCT' list of a field from a table / view (with 'WHERE' criteria) and alongside that count the number of times that that field content repeats in the table / view?
In other words, I have an initial view that looks a bit like this:
I'd like a single SQL query to filter it (SELECT...WHERE...) so that we are only considering records where [ORDER COMPLETE] = False and [PERSONAL] = Null...
...and then create a distinct list of names with counts of the number of times each name appears in the previous table:
*Displaying the [ORDER COMPLETE] and [PERSONAL] fields is redundant by this point and could be dropped to simplify.
I can do the steps individually as above, but struggling to get a single query to do it all... any help appreciated!
Thanks in advance,
-Tim
This should just be the following
SELECT dbo.tblPerson.Person,
COUNT(dbo.tblPerson.Person) AS Count
FROM dbo.tblPerson
INNER JOIN dbo.tblNotifications ON dbo.tblPerson.PersonID = dbo.tblNotifications.AddresseeID
WHERE dbo.tblNotifications.Complete = 'False'
AND dbo.tblNotifications.Personal IS NULL
GROUP BY dbo.tblPerson.Person
ORDER BY COUNT(dbo.tblPerson.Person) DESC
You don't need your DISTINCT or TOP 100 PERCENT,
Here is a simplified fiddle
Well I got downvoted into oblivion (probably for displaying the full extent of my own ignorance!), but just in case someone from the future experiences the same problem as me and stumbles across this question while Googling (or whatever verb you use for "searching all digitised human knowledge" in the distant future), here's some sanitised code of the query I managed to get to work in the end - thanks to Mark Sinkinson's snippet for helping me realise the obvious...
SELECT DISTINCT TOP (100) PERCENT dbo.tblPerson.Person, COUNT(dbo.tblPerson.Person) AS CountPerson
FROM dbo.tblPerson INNER JOIN
dbo.tblNotifications ON dbo.tblPerson.PersonID = dbo.tblNotifications.AddresseeID
WHERE (dbo.tblNotifications.Complete = 'False') AND (dbo.tblNotifications.Personal IS NULL)
GROUP BY dbo.tblPerson.Person
ORDER BY CountPerson DESC

Old Join Syntax multiple tables

I'm trying to join four tables together using the old inner join syntax in sql server 2008 and can't figure it out, I keep getting a cartesian product. I've tried multiple different ways but still get repeating results.
where's my error?
code:
SELECT
TC.intCustomerID
,TC.strFirstName + ',' + TC.strLastName AS strCustomer
,TCO.intOrderIndex
,TCO.dtmOrder
,TI.intItemID
,TI.strItem
,TCOI.intQuantity
FROM
TCustomers AS TC
,TCustomerOrders AS TCO
,TCustomerOrderItems AS TCOI
,TItems AS TI
WHERE
TC.intCustomerID = TCOI.intCustomerID
AND TCO.intOrderIndex = TCOI.intOrderIndex
AND TCOI.intItemID = TI.intItemID
ORDER BY
TC.intCustomerID
,strCustomer
i don't know your tables but it looks strange to read WHERE
TC.intCustomerID = TCOI.intCustomerID for the first table, i guess it should be WHERE
TC.intCustomerID = TCO.intCustomerID ?
If TCustomers (TC) contains all your customers and TCustomerOrders (TCO) your orders, i guess the order is linked to a customer?
Your query looks to link directly the customer to the order's items, which might be wrong if the order has more than one item.
By the way, why is the customer ID stored in the TCustomerOrderItems table?
I might be totally wrong, you should give some sample datas as others said though

SQL query join elements

I will re-write my doubt to be more easy to understand.
I have one table named SeqNumbers that have only one column of data named PossibleNumbers, that has value from 1 to 10.000.
Then I have another Table named Terminals and one of the columns have the serial numbers of the terminals. What I want is get all the SerialNumbers that not exists in the Terminals table from 1 to 10.000.
I've created the SeqNumbers table only to do this... maybe there's another solution without using it... that's fine to me.
The query I have is:
SELECT PossibleNumbers from SeqNumbers
Where PossibleNumbers NOT IN (SELECT SerialNumbers from Terminals)**
Basically I want to list ALL serial numbers of terminals that doesn't exists in the database.
This Query works fine I think... but the problem is that I don't want all results in a single column.. I want these results displayed in 4 or 5 columns.
For my purpose I can only use the results from the query like that. I cannot use programmatically methods to do that.
Hope this is more clear now... Thanks for all the help...
select x, x+1000 from tablename
Will that do it for you?
If I'm reading this right, you'd probably have to do a self join; something like:
SELECT
LeftValues.ColA,
RightValues.ColA AS ColB
FROM YourTable LeftValues
LEFT JOIN YourTable RightValues ON LeftValues.ColA = RightValues.ColA - 1000
WHERE LeftValues.ColA < 1000
Note: Use the JOIN that makes sense for you (left if you are willing to accept NULLs in ColB, inner if you only want them where both values exist)
You can use a scripting language to parse the MySQL results to format it anyway you like. Are you using PHP to access the database? If so, let me know and I can cook one up for you.
I just saw your new updated question. In this case the order of the columns will be ordered by your SELECT statement and you can also sort too. Here is an example:
SELECT Column1, Column2 FROM my_table ORDER BY Column1, Column2 ASC

Resources