Reputation: 91
This site has been super helpful with this database i am creating for work, i have a lot of VB knowledge but little SQL.
i am creating a database of cisco IP phones which records the MACs, serials and to what site id they are assigned to.
My managers have now decided to change the goal posts of my application once again and are now asking for me to create a form that displays data in a way i have no idea how to do.
what they now want and what i am hoping to achieve somehow is to create a sql statement that gets the count of the number handsets by site id and then to compare that number against the data from another table.
Here is the fields that we need to work with:
TABLE 1
Handset_Type
Handset_Site_Id
TABLE 2
Handset_Type
Handset_Site_Id
This is how i would like to display the data
SITE ID | Handset_Type1 | Handset_Type1
Handset_Site_id1 |COUNT TYPE1 FROM T1|COUNT TYPE1 FROM T2
Handset_Site_id2 |COUNT TYPE1 FROM T1|COUNT TYPE1 FROM T2
If we can use the data in the Handset_type field to create the column headings then that would be great as there are only a few models of phones but if they are static columns then that will be ok also.
I hope i have explained this ok as i can see this may be complex to understand.
if you have any suggestions please let me know
Thank you
Steve
Upvotes: 0
Views: 4198
Reputation: 3047
If I understand the question correctly, you would like to present the count of records from both tables, with the handset type and source table as column headings, for each site ID.
The first step is to merge your tables into a single table, creating a column which expresses the handset type and source table:
SELECT Handset_Type & " in T1" as TypeFromT, Handset_Site_Id FROM [Table 1]
UNION ALL
SELECT Handset_Type & " in T2" as TypeFromT, Handset_Site_Id FROM [Table 2]
This will form an inner query for the crosstab. The syntax for crosstabs can be a bit tricky so I usually build mine in design view. We define the TypeFromT
as our new column heading and we use Handset_Site_Id
both as our row groupings and as our counting field:
TRANSFORM Count(SubQry.Handset_Site_Id) AS SiteIDCount
SELECT SubQry.Handset_Site_Id
FROM (
SELECT Handset_Type & " in T1" as TypeFromT, Handset_Site_Id FROM [Table 1]
UNION ALL
SELECT Handset_Type & " in T2" as TypeFromT, Handset_Site_Id FROM [Table 2]
) AS SubQry
GROUP BY SubQry.Handset_Site_Id
PIVOT SubQry.TypeFromT;
The only catch is that if there are zero entries for the particular Handset Type, Source Table, and Site ID, the resulting value will be null instead of a 0. If that is undesirable, replace Count(SubQry.Handset_Site_Id)
with Nz(Count(SubQry.Handset_Site_Id),0)
Upvotes: 1