Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 DISTINCT and DCOUNT problem

Author  Topic 

wjyoung
Starting Member

2 Posts

Posted - 2011-10-18 : 18:02:24
Hello forum,

I have measurement data in a table for purchased items. The data are recorded against the item ID and the lot ID. There will be any number of items, lots per item, and records per lot. For example:

(myTable)
ItemID, LotID, Measurement
PartA, LotA.1, DataA.1.1
PartA, LotA.1, DataA.1.2
PartA, LotA.2, DataA.2.1
PartB, LotB.1, DataB.1.1
PartB, LotB.1, DataB.1.2
PartB, LotB.1, DataB.1.3

I want to count the number of measurement for each distinct ItemID+LotID combination.

ItemID, LotID, MeasurementCount
PartA, LotA.1, 2
PartA, LotA.2, 1
PartB, LotB.1, 3

I'm controlling which ItemID to display with combo box called "PickItemID" on a form called "Data Form". Here is my SQL:

quote:
SELECT DISTINCT myTable.ItemID, myTable.LotID, DCount("ItemID","myTable","ItemID = '" & [Forms]![Data Form]![PickItemID] & "'") AS Expr1
FROM myTable
WHERE (((myTable.ItemID)=[Forms]![Data Form]![PickItemID]));


The (undesired) result is:

ItemID, LotID, MeasurementCount
PartA, LotA.1, 3
PartA, LotA.2, 3
PartB, LotB.1, 3

It is counting all of the "PartA" records together, regardless of the LotID. How do I get a DCount for the combination of ItemID and LotID?

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2011-10-18 : 18:03:43
Don't use DISTINCT for this, instead use GROUP BY.

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page

wjyoung
Starting Member

2 Posts

Posted - 2011-10-18 : 18:30:24
quote:
Originally posted by tkizer

Don't use DISTINCT for this, instead use GROUP BY.



Thanks. Here's the SQL I used:

SELECT myTable.ItemID, myTable.LotID, Count(myTable.Measurement) AS CountOfMeasurements
FROM myTable
GROUP BY myTable.ItemID, myTable.WeighDate;
Go to Top of Page

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2011-10-18 : 19:00:31
You're welcome, glad to help.


Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page
   

- Advertisement -