Displaying a zero when no stock is held - ms-access-2013

I have a simple query that shows books written by a particular author, and counts the total number of books held in stock. The result returned from the query shows five columns. BookID, AuthorID, AuthorName, BookName and the total books held in stock.
My problem is that if a particular book has no stock held, the book name is not displayed in the result. I want the bookname displayed with a zero shown.
i.e.
1 1 Lee Child Personal 5
1 2 Lee Child Make Me 4
1 3 Lee Child The Visitor 0
1 4 Lee child One Shot 8
The sql for the query is shown below:
SELECT tblSale.BookID, tblAuthor.AuthorID, tblAuthor.AuthorName,
tblBook.BookName, Count(tblBook.BookName) AS [In Stock]
FROM (tblAuthor INNER JOIN tblBook ON tblAuthor.AuthorID = tblBook.AuthorID)
INNER JOIN tblSale ON tblBook.BookID = tblSale.BookID
GROUP BY tblSale.BookID, tblAuthor.AuthorID, tblAuthor.AuthorName,
tblBook.BookName, tblSale.BookInStock
HAVING (((tblAuthor.AuthorID)=[forms]![frmMain]![text12]) AND
((tblSale.BookInStock)=Yes))
ORDER BY tblAuthor.AuthorName;
I'd be very grateful for a solution to this irritating problem! Many thanks...

It's had to say without more info but your query has
(tblSale.BookInStock)=Yes)
Isn't that filtering out all the no s
Something like this (Just the Zero Stock Books) ?
SELECT tblSale.BookID, tblAuthor.AuthorID, tblAuthor.AuthorName,
tblBook.BookName, Count(tblBook.BookName) AS [In Stock]
FROM (tblAuthor INNER JOIN tblBook ON tblAuthor.AuthorID = tblBook.AuthorID)
INNER JOIN tblSale ON tblBook.BookID = tblSale.BookID
Where [In Stock] = 0
GROUP BY tblSale.BookID, tblAuthor.AuthorID, tblAuthor.AuthorName,
tblBook.BookName, tblSale.BookInStock
ORDER BY tblAuthor.AuthorName;
or (All Books Including Zero Stock)
SELECT tblSale.BookID, tblAuthor.AuthorID, tblAuthor.AuthorName,
tblBook.BookName, Count(tblBook.BookName) AS [In Stock]
FROM (tblAuthor INNER JOIN tblBook ON tblAuthor.AuthorID = tblBook.AuthorID)
INNER JOIN tblSale ON tblBook.BookID = tblSale.BookID
GROUP BY tblSale.BookID, tblAuthor.AuthorID, tblAuthor.AuthorName,
tblBook.BookName, tblSale.BookInStock
ORDER BY tblAuthor.AuthorName;

Related

LEFT JOIN three tables and SUM in LINQ

I have three tables:
products purchased (RecordEntered as A)
products sold in the country (SoldInCountry as B)
products sold outside the country (SoldOutCountry as C)
Each record in A could be:
entered and not yet sold
entered and sold only in the country
entered and sold only out of the country
entered and sold in the country and also outside the country
I started grouping the pieces in table B like so:
SELECT
A.IdRecord, A.Qty, sum(isnull(B.Qty,0)) AS Expr1
FROM
RecordEntered AS A
LEFT OUTER JOIN
SoldInCountry AS B ON A.IdRecord = B.IdRecord
group by A.IdRecord, A.Qty
But I do not know how to go on.
I would like a query to show me how many pieces I still have in stock.
Like this:
A.Qty - (SUM(ISNULL(B.Qty, 0)) + SUM(ISNULL(C.Qty, 0)))
I wrote an example in SQL, but the goal is LINQ:
from a in _ctx.....
where .....
select...
thanks
It isn't easy to do a full outer join in LINQ (see my answer here: https://stackoverflow.com/a/43669055/2557128) but you don't need that to solve this:
var numInStock = from item in RecordEntered
select new {
item.Code,
Qty = item.Qty - (from sic in SoldInCountry where sic.IdRecord == item.IdRecord select sic.Qty).SingleOrDefault() -
(from soc in SoldOutCountry where soc.IdRecord == item.IdRecord select soc.Qty).SingleOrDefault()
};
I assumed there would only be one sold record of each type for an item, if there could be more than one, you would need to Sum the matching records:
var numInStock = from item in RecordEntered
select new {
item.Code,
Qty = item.Qty - (from sic in SoldInCountry where sic.IdRecord == item.IdRecord select sic.Qty).DefaultIfEmpty().Sum() -
(from soc in SoldOutCountry where soc.IdRecord == item.IdRecord select soc.Qty).DefaultIfEmpty().Sum()
};

Only want to return rows that have duplicate unitid within group by unitid

I am working in SSRS querying against an oracle database.
So I have a data source and this report is supposed to find duplicate Work Orders based on multiple open workorders on a unique unitid. So I only want to show groups that have more then one entry as they are grouped by unitid.
SELECT
COMPSTSB.UNITID,
COMPSTSB.UNITTYPE,
ACTDEFN.ACTDESC,
ACTDEFN.ACTCODE,
HISTORY.WONO,
HISTORY.COMPFLAG,
HISTORY.ADDDTTM,
HISTORY.COMMENTS
FROM (IMSV7.COMPSTSB COMPSTSB INNER JOIN IMSV7.HISTORY HISTORY ON
COMPSTSB.COMPKEY=HISTORY.COMPKEY) INNER JOIN IMSV7.ACTDEFN ACTDEFN ON
HISTORY.ACTKEY=ACTDEFN.ACTKEY
WHERE HISTORY.COMPFLAG='Y' AND NOT (ACTDEFN.ACTCODE='DBR' OR ACTDEFN.ACTCODE='IN')
ORDER BY COMPSTSB.UNITTYPE, COMPSTSB.UNITID, HISTORY.ADDDTTM
Can anyone point me in the right direction? And yes before someone says this has been asked a million times, I did search. Point me to the million times and I will see if I feel they match my question. Ideally in the SQL I could make new column that returned a count of the unitid and I did attempt this but failed, and then I could filter on that column to remove any that only had one count. I really don't think this should be difficult but I have spent about 4 hours on it so far.
Thanks in advance!
Steven
If I understood your question right, the following should give you what's needed :
SELECT * FROM
(
SELECT
COMPSTSB.UNITID,
COMPSTSB.UNITTYPE,
ACTDEFN.ACTDESC,
ACTDEFN.ACTCODE,
HISTORY.WONO,
HISTORY.COMPFLAG,
HISTORY.ADDDTTM,
HISTORY.COMMENTS,
COUNT(1) OVER (PARTITION BY COMPSTSB.UNITID) AS numDups
FROM (IMSV7.COMPSTSB COMPSTSB INNER JOIN IMSV7.HISTORY HISTORY ON
COMPSTSB.COMPKEY=HISTORY.COMPKEY) INNER JOIN IMSV7.ACTDEFN ACTDEFN ON
HISTORY.ACTKEY=ACTDEFN.ACTKEY
WHERE HISTORY.COMPFLAG='Y' AND NOT (ACTDEFN.ACTCODE='DBR' OR ACTDEFN.ACTCODE='IN')
)a
WHERE a.numDups >1
ORDER BY COMPSTSB.UNITTYPE, COMPSTSB.UNITID, HISTORY.ADDDTTM
I expect you are concerned about having duplicate values of UNITID in the IMSV7.COMPSTSB table. If so adding this join to your query should enable ou to identify them:
JOIN (SELECT COMPSTSB.UNITID
FROM IMSV7.COMPSTSB
GROUP BY COMPSTSB.UNITID
HAVING COUNT(COMPSTSB.UNITID) > 1) dups
ON DUPS.UNITID = COMPSTSB.UNITID
JOIN IMSV7.HISTORY HISTORY
Here's the full query:
SELECT COMPSTSB.UNITID
, COMPSTSB.UNITTYPE
, ACTDEFN.ACTDESC
, ACTDEFN.ACTCODE
, HISTORY.WONO
, HISTORY.COMPFLAG
, HISTORY.ADDDTTM
, HISTORY.COMMENTS
FROM IMSV7.COMPSTSB COMPSTSB
JOIN (SELECT COMPSTSB.UNITID
FROM IMSV7.COMPSTSB
GROUP BY COMPSTSB.UNITID
HAVING COUNT(COMPSTSB.UNITID) > 1) dups
ON DUPS.UNITID = COMPSTSB.UNITID
JOIN IMSV7.HISTORY HISTORY
ON COMPSTSB.COMPKEY = HISTORY.COMPKEY
JOIN IMSV7.ACTDEFN ACTDEFN
ON HISTORY.ACTKEY = ACTDEFN.ACTKEY
WHERE HISTORY.COMPFLAG = 'Y'
AND ACTDEFN.ACTCODE NOT IN ('DBR','IN')
ORDER BY COMPSTSB.UNITTYPE
, COMPSTSB.UNITID
, HISTORY.ADDDTTM;
Since the above query didn't work you can try outer joins to similar sub queries on each of your tables and limit to only records where the outer joined table returns data. This will show you which tables in your query are cuasing your extra rows.:
SELECT COMPSTSB.UNITID
, COMPSTSB.UNITTYPE
, ACTDEFN.ACTDESC
, ACTDEFN.ACTCODE
, HISTORY.WONO
, HISTORY.COMPFLAG
, HISTORY.ADDDTTM
, HISTORY.COMMENTS
, DUPS.UNITID UNITID_DUP
, DUPS2.COMPKEY COMPKEY_DUP
, DUPS3.ACTKEY ACTKEY_DUP
FROM IMSV7.COMPSTSB COMPSTSB
JOIN IMSV7.HISTORY HISTORY
ON COMPSTSB.COMPKEY = HISTORY.COMPKEY
JOIN IMSV7.ACTDEFN ACTDEFN
ON HISTORY.ACTKEY = ACTDEFN.ACTKEY
LEFT JOIN (SELECT COMPSTSB.UNITID
FROM IMSV7.COMPSTSB
GROUP BY COMPSTSB.UNITID
HAVING COUNT(COMPSTSB.UNITID) > 1) dups
ON DUPS.UNITID = COMPSTSB.UNITID
LEFT JOIN (SELECT HISTORY.COMPKEY
FROM IMSV7.HISTORY
GROUP BY HISTORY.COMPKEY
HAVING COUNT(HISTORY.COMPKEY) > 1) dups2
ON DUPS.UNITID = COMPSTSB.UNITID
LEFT JOIN (SELECT ACTDEFN.ACTKEY
FROM IMSV7.ACTDEFN
GROUP BY ACTDEFN.ACTKEY
HAVING COUNT(ACTDEFN.ACTKEY) > 1) dups3
ON DUPS.UNITID = COMPSTSB.UNITID
WHERE HISTORY.COMPFLAG = 'Y'
AND ACTDEFN.ACTCODE NOT IN ('DBR','IN')
AND ( DUPS.UNITID IS NOT NULL OR
DUPS2.COMPKEY IS NOT NULL OR
DUPS3.ACTKEY IS NOT NULL)
ORDER BY COMPSTSB.UNITTYPE
, COMPSTSB.UNITID
, HISTORY.ADDDTTM;

Why And in joining clause not filtering the data

The below code is written to get the all the parent and child relationship and want to understand why the And is not filtering the records but where does.
e.g-
select
s.name,
s.status,
s.start_date_active,
s.end_date_active,
s.salesrep_number,
p.name Parent_name,
p.status Parent_status,
p.start_date_active Parent_start_date_active,
p.end_date_active Parent_end_date_active,
FROM XXX_XX_SALESREPS s
left outer join XXX_XX_SALESREPS p
on s.attribute1 = p.salesrep_id
**and s.attribute1 = '100003916'**
this above query give all the rows from table s and do not filter it on '100003916' . But when i used ..
select
s.name,
s.status,
s.start_date_active,
s.end_date_active,
s.salesrep_number,
p.name Parent_name,
p.status Parent_status,
p.start_date_active Parent_start_date_active,
p.end_date_active Parent_end_date_active,
FROM XXX_XX_SALESREPS s
left outer join XXX_XX_SALESREPS p
on s.attribute1 = p.salesrep_id
**where s.attribute1 = '100003916'**
this query gives me just filter record. Why can anyone please answer it. Thanks in advance.
In your first case and s.attribute1 = '100003916' is part of your join criteria - and since it is left outer join it wont serve as a filter.

Tsql: what is the best way to retrieve some records with a specific criteria?

I have a table (Cars) which saves some characteristics car like EngineNo, LastProductionStepId, NodyNo, ...
Besides, I have another table (CarSteps) which saves all steps that a specific car should pass during its manufacturing proccess like Engine Assigning(Id = 2), Engraving(3), PrePaint(4), Paint(5), AfterPaint(6), Confirmation(7), Delivery(8)
I would like to get all cars that are between PrePaint and Confirmation at the moment:
select cr.Id, cr.BodyNo, cr.LastStepId
from Cars cr WITH (NOLOCK)
inner join CarSteps steps WITH (NOLOCK) on cr.Id = trace.CarId and cr.LastStepId=trace.StepId
where
cr.LastStepId >= 4
AND cr.[Status] = 1
AND steps.[Status] = 1
AND not exists ( select *
from CarSteps steps1 WITH (NOLOCK)
where steps1.CarId = cr.Id
AND steps1.StepId >= 7 AND steps1.Status = 1
)
Because CarSteps has many records (44 million) the query is slow .
what is your opinion? is there any better way to get those cars?
Looking at your query I see a join from Cars to CarSteps, I see you joining to trace.CarId and trace.StepId is. trace is not defined in your query.
from
Cars cr WITH (NOLOCK) inner join
CarSteps steps WITH (NOLOCK) on
cr.Id = trace.CarId and
cr.LastStepId=trace.StepId
I may be able to help if i have better understand the fully query.
What does the execution plan reveal?

Linq-to-entities - Include() method not loading

If I use a join, the Include() method is no longer working, eg:
from e in dc.Entities.Include("Properties")
join i in dc.Items on e.ID equals i.Member.ID
where (i.Collection.ID == collectionID)
select e
e.Properties is not loaded
Without the join, the Include() works
Lee
UPDATE: Actually I recently added another Tip that covers this, and provides an alternate probably better solution. The idea is to delay the use of Include() until the end of the query, see this for more information: Tip 22 - How to make include really include
There is known limitation in the Entity Framework when using Include().
Certain operations are just not supported with Include.
Looks like you may have run into one on those limitations, to work around this you should try something like this:
var results =
from e in dc.Entities //Notice no include
join i in dc.Items on e.ID equals i.Member.ID
where (i.Collection.ID == collectionID)
select new {Entity = e, Properties = e.Properties};
This will bring back the Properties, and if the relationship between entity and Properties is a one to many (but not a many to many) you will find that each resulting anonymous type has the same values in:
anonType.Entity.Properties
anonType.Properties
This is a side-effect of a feature in the Entity Framework called relationship fixup.
See this Tip 1 in my EF Tips series for more information.
Try this:
var query = (ObjectQuery<Entities>)(from e in dc.Entities
join i in dc.Items on e.ID equals i.Member.ID
where (i.Collection.ID == collectionID)
select e)
return query.Include("Properties")
So what is the name of the navigation property on "Entity" which relates to "Item.Member" (i.e., is the other end of the navigation). You should be using this instead of the join. For example, if "entity" add a property called Member with the cardinality of 1 and Member had a property called Items with a cardinality of many, you could do this:
from e in dc.Entities.Include("Properties")
where e.Member.Items.Any(i => i.Collection.ID == collectionID)
select e
I'm guessing at the properties of your model here, but this should give you the general idea. In most cases, using join in LINQ to Entities is wrong, because it suggests that either your navigational properties are not set up correctly, or you are not using them.
So, I realise I am late to the party here, however I thought I'd add my findings. This should really be a comment on Alex James's post, but as I don't have the reputation it'll have to go here.
So my answer is: it doesn't seem to work at all as you would intend. Alex James gives two interesting solutions, however if you try them and check the SQL, it's horrible.
The example I was working on is:
var theRelease = from release in context.Releases
where release.Name == "Hello World"
select release;
var allProductionVersions = from prodVer in context.ProductionVersions
where prodVer.Status == 1
select prodVer;
var combined = (from release in theRelease
join p in allProductionVersions on release.Id equals p.ReleaseID
select release).Include(release => release.ProductionVersions);
var allProductionsForChosenRelease = combined.ToList();
This follows the simpler of the two examples. Without the include it produces the perfectly respectable sql:
SELECT
[Extent1].[Id] AS [Id],
[Extent1].[Name] AS [Name]
FROM [dbo].[Releases] AS [Extent1]
INNER JOIN [dbo].[ProductionVersions] AS [Extent2] ON [Extent1].[Id] = [Extent2].[ReleaseID]
WHERE ('Hello World' = [Extent1].[Name]) AND (1 = [Extent2].[Status])
But with, OMG:
SELECT
[Project1].[Id1] AS [Id],
[Project1].[Id] AS [Id1],
[Project1].[Name] AS [Name],
[Project1].[C1] AS [C1],
[Project1].[Id2] AS [Id2],
[Project1].[Status] AS [Status],
[Project1].[ReleaseID] AS [ReleaseID]
FROM ( SELECT
[Extent1].[Id] AS [Id],
[Extent1].[Name] AS [Name],
[Extent2].[Id] AS [Id1],
[Extent3].[Id] AS [Id2],
[Extent3].[Status] AS [Status],
[Extent3].[ReleaseID] AS [ReleaseID],
CASE WHEN ([Extent3].[Id] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [C1]
FROM [dbo].[Releases] AS [Extent1]
INNER JOIN [dbo].[ProductionVersions] AS [Extent2] ON [Extent1].[Id] = [Extent2].[ReleaseID]
LEFT OUTER JOIN [dbo].[ProductionVersions] AS [Extent3] ON [Extent1].[Id] = [Extent3].[ReleaseID]
WHERE ('Hello World' = [Extent1].[Name]) AND (1 = [Extent2].[Status])
) AS [Project1]
ORDER BY [Project1].[Id1] ASC, [Project1].[Id] ASC, [Project1].[C1] ASC
Total garbage. The key point to note here is the fact that it returns the outer joined version of the table which has not been limited by status=1.
This results in the WRONG data being returned:
Id Id1 Name C1 Id2 Status ReleaseID
2 1 Hello World 1 1 2 1
2 1 Hello World 1 2 1 1
Note that the status of 2 is being returned there, despite our restriction. It simply does not work.
If I have gone wrong somewhere, I would be delighted to find out, as this is making a mockery of Linq. I love the idea, but the execution doesn't seem to be usable at the moment.
Out of curiosity, I tried the LinqToSQL dbml rather than the LinqToEntities edmx that produced the mess above:
SELECT [t0].[Id], [t0].[Name], [t2].[Id] AS [Id2], [t2].[Status], [t2].[ReleaseID], (
SELECT COUNT(*)
FROM [dbo].[ProductionVersions] AS [t3]
WHERE [t3].[ReleaseID] = [t0].[Id]
) AS [value]
FROM [dbo].[Releases] AS [t0]
INNER JOIN [dbo].[ProductionVersions] AS [t1] ON [t0].[Id] = [t1].[ReleaseID]
LEFT OUTER JOIN [dbo].[ProductionVersions] AS [t2] ON [t2].[ReleaseID] = [t0].[Id]
WHERE ([t0].[Name] = #p0) AND ([t1].[Status] = #p1)
ORDER BY [t0].[Id], [t1].[Id], [t2].[Id]
Slightly more compact - weird count clause, but overall same total FAIL.
Has anybody actually ever used this stuff in a real business application? I'm really starting to wonder...
Please tell me I've missed something obvious, as I really want to like Linq!
Try the more verbose way to do more or less the same thing obtain the same results, but with more datacalls:
var mydata = from e in dc.Entities
join i in dc.Items
on e.ID equals i.Member.ID
where (i.Collection.ID == collectionID)
select e;
foreach (Entity ent in mydata) {
if(!ent.Properties.IsLoaded) { ent.Properties.Load(); }
}
Do you still get the same (unexpected) result?
EDIT: Changed the first sentence, as it was incorrect. Thanks for the pointer comment!

Resources