I'm trying to develop a simple query in which I'm trying to do Count of distinct values from a field, i have tried to use DISTINCT in query which throws error.
Please guide me to fix this code, thanks.
SELECT TSData.[Upd Bay], Sum(TSData.RT) AS RT, Sum(TSData.OT) AS OT, Count(DISTINCT TSData.[EMP No]) AS EmpCount
FROM TSData
WHERE (((TSData.[TS Date])=Nz([Forms]![TSDataDeptSummary]![CmbTSDate],Date()-1)))
GROUP BY TSData.[Upd Bay];
enter image description here
You can separately query those parts and combine as subqueries:
select A.[Upd Bay], A.[TS Date], DCnt.EmpCnt
from
(
SELECT A.[Upd Bay], A.[TS Date]
FROM TSData A
WHERE A.[Ts Date]=Nz([Forms]![TSDataDeptSummary]![CmbTSDate],Date()-1)
group by A.[Upd Bay], A.[TS Date]
) A
inner join
(
select [Upd Bay], count([Emp No]) as EmpCnt
from (
select distinct B.[Upd Bay], B.[Emp No]
from TSData B
where B.[Ts Date]=Nz([Forms]![TSDataDeptSummary]![CmbTSDate],Date()-1)
) as Dnt
group by [Upd Bay]
) as DCnt
on A.[Upd Bay]=DCnt.[Upd Bay]
Related
SELECT [order id],
pickingdate
FROM td_order1
WHERE sku = xyz
GROUP BY pickingdate,
[order id]
HAVING pickingdate >= Min(pickingdate)
AND pickingdate <= Max(pickingdate)
ORDER BY pickingdate
Is there anything wrong in this query?
What is wrong with the query is that you are using unaggregated columns in the having. My recommendation is to use window functions:
SELECT o.*
FROM (SELECT o.*,
MIN(pickingdate) OVER (PARTITION BY sku) as min_pd,
MAX(pickingdate) OVER (PARTITION BY sku) as max_pd
FROM td_order1 o
WHERE sku = xyz
) o
WHERE pickingdate > min_pd and pickingdate < max_pd
ORDER BY pickingdate;
Modify your condition as :
pickingdate < Max(pickingdate)
to exclude end date
The following query displays duplicates in a table with the qty alias showing the total count, eg if there are five duplicates then all five will have the same qty = 5.
select s.*, t.*
from [Migrate].[dbo].[Table1] s
join (
select [date] as d1, [product] as h1, count(*) as qty
from [Migrate].[dbo].[Table1]
group by [date], [product]
having count(*) > 1
) t on s.[date] = t.[d1] and s.[product] = t.[h1]
ORDER BY s.[product], s.[date], s.[id]
Is it possible to amend the count(*) as qty to show an incremental count so that five duplicates would display 1,2,3,4,5?
The answer to your question is row_number(). How you use it is rather unclear, because you provide no guidance, such as sample data or desired results. Hence this answer is rather general:
select s.*, t.*,
row_number() over (partition by s.product order by s.date) as seqnum
from [Migrate].[dbo].[Table1] s join
(select [date] as d1, [product] as h1, count(*) as qty
from [Migrate].[dbo].[Table1]
group by [date], [product]
having count(*) > 1
) t
on s.[date] = t.[d1] and s.[product] = t.[h1]
order by s.[product], s.[date], s.[id];
The speculation is that the duplicates are by product. This enumerates them by date. Some combination of the partition by and group by is almost certainly what you need.
I have looked through the forum and can find a variety of examples to solve my problem but just cannot put everything together.
My situation is typical that I would like to show the Top 10 customers (Orders.[Customer Name]) by group (Shop_Lookup.ShopGroup]) for their total revenue.
I can get so far in producing the overall Top 10 regardless of ShopGroup but just cannot get my head around getting the Sub Query to work. My current code is -
SELECT TOP 10 Orders.[Customer Name],
Sum(Orders.[Actual Revenue]) AS [SumOfActual Revenue],
Orders.[This Month],
Shop_Lookup.[ShopGroup]
FROM Orders
INNER JOIN Shop_Lookup ON Orders.[ShopID] = ShopLookup.[ShopID]
WHERE ((Orders.[This Month])="current")
GROUP BY Orders.[Customer Name], Orders.[This Month], Shop_Lookup.[ShopGroup]
ORDER BY Sum(Orders.[Actual Revenue]) DESC;
Completely AIR CODED ! Proceed with caution.
You can use Sub Query to get this !
SELECT
Orders.[Customer Name],
Sum(Orders.[Actual Revenue]) AS [SumOfActual Revenue],
Orders.[This Month],
Shop_Lookup.[ShopGroup]
FROM
Orders
INNER JOIN
Shop_Lookup
ON
Orders.[ShopID] = ShopLookup.[ShopID]
WHERE
(
(Orders.[This Month] = 'Current')
AND
(Orders.ShopID IN
(SELECT
TOP 10 ShopID
FROM
Orders AS Dupe
WHERE
Dupe.ShopID = Orders.ShopID
)
)
)
GROUP BY
Orders.[Customer Name],
Orders.[This Month],
Shop_Lookup.[ShopGroup]
ORDER BY
Sum(Orders.[Actual Revenue]) DESC;
More information on Subqueries : http://allenbrowne.com/subquery-01.html
I've created the following but it keeps coming up with the error message You tried to execute a query that does not include the specified expression 'ICE Team' as part of an aggregate function.
SELECT ztSub.[Master Sheet].[ICE Team], ztSub.[date], Count(ztSub.[Count])
FROM (SELECT [Master Sheet].[ICE Team],[Master Sheet].[Visit Date (planned for)] AS [date],Count([Master Sheet]![Visit Date (planned for)]) AS [Count]
FROM [Master Sheet]
UNION
SELECT [Master Sheet].[ICE Team],[Master Sheet].[Date retasked to?] AS [date], Count ([Master Sheet]![Date retasked to?]) AS [Count]
FROM [Master Sheet] ) AS ztSub
GROUP BY ztSub.[Master Sheet].[ICE Team];
This now works. I incorporated a sum of the [Count of Dates] and its given me my results.
SELECT [Total].[Ice Team] AS [Ice Team], ztSub.Period, Sum(ztSub.[Count of Dates]) AS [SumOfCount of Dates]
FROM (SELECT Total.[Ice Team], Total.[Re-Visited] AS Period, Count([Total]![Re-Visited]) AS [Count of Dates]
FROM Total
GROUP BY [Ice Team], [Re-Visited]
UNION SELECT Total.[Ice Team], Total.Visited AS Period, Count([Total]![Visited]) AS [Count of Dates]
FROM Total
GROUP BY [Ice Team], Visited) AS ztSub
GROUP BY [Total].[Ice Team], ztSub.Period;
If the only result you are looking for is a list of dates and count of occurences, you might want to try a query with a union:
SELECT date, count(*)
FROM (
(SELECT date_col1 AS date
FROM table1)
UNION
(SELECT date_col2 AS date
FROM table1) )
GROUP BY date
EDIT FOR UPDATED QUESTION:
Your error comes from the fact that you do the count in your inner queries but the group by on your outer query. If you look at one of your inner queries separately:
SELECT [Master Sheet].[ICE Team],[Master Sheet].[Visit Date (planned for)] AS [date],Count([Master Sheet]![Visit Date (planned for)]) AS [Count]
FROM [Master Sheet]
then we still get the same exact error. This is caused by the fact that you do a count of your dates in the select clause without specifying what to do with the [ICE Team] value. You might want to include a group by-clause for the [ICE Team] value. You already did for the outer query, but it should be done in this inner query too. Same goes for your Visit Date (planned for) value, otherwise you'll get the same error for that one.
Try this query, although I'm not sure it'll give the results as you want them too. (For that, you'd have to add a clear example of input and expected output to your question.)
SELECT ztSub.[Master Sheet].[ICE Team], ztSub.[date], Count(ztSub.[Count])
FROM (SELECT [Master Sheet].[ICE Team],[Master Sheet].[Visit Date (planned for)] AS [date],Count([Master Sheet]![Visit Date (planned for)]) AS [Count]
FROM [Master Sheet]
group by [ICE Team],[Visit Date (planned for)]
UNION
SELECT [Master Sheet].[ICE Team],[Master Sheet].[Date retasked to?] AS [date], Count ([Master Sheet]![Date retasked to?]) AS [Count]
FROM [Master Sheet]
group by [ICE Team], [Date retasked to?] ) AS ztSub
GROUP BY ztSub.[Master Sheet].[ICE Team],date;
I'm trying to develop a time sheet page on my web site, and this is my database stracture:
I want to get total hours(TimeSheetWeeks table's sum(timeFrom-timeTo)), total expense(TimeSheetWeeks's table's total amount) and total(TimSheetWeeks table's total amount+ compAllow table's total Amount).
This is my query I wrote to get my result:
;WITH w(tot, tid, eid, fd, td, am, mw) AS
(
SELECT Total = tsw.amount+ca.amount , tsw.[TimeSheetID], [EmployeeID],
[FromDate],[ToDate], tsw.[Amount], SUM(DATEDIFF(MINUTE, [timeFrom],[timeTo] ))
FROM
TimeSheet ts
INNER JOIN (
SELECT SUM(amount) amount, TimeSheetID
FROM TimeSheetWeeks
GROUP BY TimeSheetID
) tsw ON ts.TimeSheetID = tsw.TimeSheetID INNER JOIN (
SELECT SUM(amount) amount, TimeSheetID
FROM CompAllow
GROUP BY TimeSheetID
) ca ON ts.TimeSheetID = ca.TimeSheetID INNER JOIN (
SELECT timeFrom, timeTo, TimeSheetID
FROM TimeSheetWeeks
) AS tss ON tss.TimeSheetID=ts.TimeSheetID
WHERE ts.TimeSheetID=6
Group By tsw.[TimeSheetID], [EmployeeID], [FromDate], [ToDate], tsw.[Amount]
)
SELECT tot, tid, eid, fd, td, Amount = am, totalHrs = RTRIM(mw/60) + ':' +
RIGHT('0'+ RTRIM(mw%60),2)
FROM w;
this quer causes an error saying
Column 'ca.amount' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
What goes wrong here? thanx in advance.
The ca.amount column is referenced in the w CTE, but is neither aggregated nor included in the GROUP BY clause:
;WITH w(tot, tid, eid, fd, td, am, mw) AS
(
SELECT Total = tsw.amount+ca.amount , tsw.[TimeSheetID], [EmployeeID],
[FromDate],[ToDate], tsw.[Amount], SUM(DATEDIFF(MINUTE, [timeFrom],[timeTo] ))
FROM
TimeSheet ts
INNER JOIN (
SELECT SUM(amount) amount, TimeSheetID
FROM TimeSheetWeeks
GROUP BY TimeSheetID
) tsw ON ts.TimeSheetID = tsw.TimeSheetID INNER JOIN (
SELECT SUM(amount) amount, TimeSheetID
FROM CompAllow
GROUP BY TimeSheetID
) ca ON ts.TimeSheetID = ca.TimeSheetID INNER JOIN (
SELECT timeFrom, timeTo, TimeSheetID
FROM TimeSheetWeeks
) AS tss ON tss.TimeSheetID=ts.TimeSheetID
WHERE ts.TimeSheetID=6
Group By tsw.[TimeSheetID], [EmployeeID], [FromDate], [ToDate], tsw.[Amount]
)
SELECT tot, tid, eid, fd, td, Amount = am, totalHrs = RTRIM(mw/60) + ':' +
RIGHT('0'+ RTRIM(mw%60),2)
FROM w;
Either add it to GROUP BY or change the Total expression like this:
Total = tsw.amount + SUM(ca.amount)
depending upon what is the business rule for this query.
The error states the problem:
SELECT SUM(amount) amount, TimeSheetID
FROM CompAllow
GROUP BY TimeSheetID
) ca ...
I'm not 100% sure, but my initial recommendation is to drop the "group by" in this clause. At best, it's redundant.
I'd also recommend trying each of the subclauses separately - make sure they're syntactically correct, make sure they're returning expected results.
IMHO...