I am trying to get the time it takes between 2 items before they are sold if that specific item had been sold more than 2 times and then how would I then be able to use the alias soldtime later for orderby
but I get this error:
Column 'sales.InvoiceDetailItem.DateTimeCreated' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
Msg 8120, Level 16, State 1, Line 4
Column 'file.Item.DateTimeCreated' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
SELECT
DATEDIFF(DAY,PS.[DateTimeCreated],P.[DateTimeCreated]) AS 'SoldTime'
, p.[Name]
, PS.[ItemCode]
, COUNT(*)
FROM
[ISTABLocalDB].[file].[Item] P
inner join [sales].[InvoiceDetailItem] PS on P.[LastInvoice_ID] = PS.Invoice_ID
GROUP BY
p.[Name], PS.[ItemCode]
HAVING
COUNT(*) >= 2
order by p.[Name]
I guess you want something like this:
SELECT
DATEDIFF(DAY,MIN(PS.[DateTimeCreated]),MAX(P.[DateTimeCreated])) AS 'SoldTime'
, p.[Name]
, PS.[ItemCode]
, COUNT(*)
FROM
[ISTABLocalDB].[file].[Item] P
inner join [sales].[InvoiceDetailItem] PS on P.[LastInvoice_ID] = PS.Invoice_ID
GROUP BY
p.[Name], PS.[ItemCode]
HAVING
COUNT(*) >= 2
order by p.[Name];
you can select count( PS.[ItemCode])
why you are using '*' ?
SELECT
DATEDIFF(DAY,PS.[DateTimeCreated],P.[DateTimeCreated]) AS 'SoldTime'
, p.[Name]
, PS.[ItemCode]
, count( PS.[ItemCode])
FROM
[ISTABLocalDB].[file].[Item] P
inner join [sales].[InvoiceDetailItem] PS on P.[LastInvoice_ID] = PS.Invoice_ID
GROUP BY
p.[Name], PS.[ItemCode]
HAVING
count( PS.[ItemCode]) >= 2
order by p.[Name]
Related
My current query returns too many lines per Subject_ID, so I want to use ROW_NUMBER() to limit the resulting set to 1 line per Subject_ID. I've added this line to my SELECT statement:
, ROW_NUMBER() over(partition by CS.Subject_ID order by CS.Subject_ID) rn
But when I try to put WHERE rn = 1 anywhere in the FROM statement, I get the error:
Incorrect syntax near the keyword 'WHERE'
And when I try to change it to AND rn = 1 (and add it on to another AND/OR line) I get the error:
Invalid column name 'rn'
So my first question is: When I add a field to my SELECT statement using that ROW_NUMBER() line, what table does this column belong to? Do I need to append it to something like Table.rn? My second question is where should I put this rn = 1 line and how should I write it in?
Full query:
SELECT
Groups.Group_Name
, CT.Created
, CT.Subject_Id
INTO #temp
FROM SubjectZ_Task CT
INNER JOIN
SubjectZ_Task_Users On CT.SubjectZ_Task_Id = SubjectZ_Task_Users.SubjectZ_Task_Id
INNER JOIN
Groups ON Groups.Group_ID = SubjectZ_Task_Users.Group_Reference
WHERE Group_Name LIKE 'Team 1'
AND CT.Created >= '1/1/2019' AND CT.Created < DATEADD(Day,1,'12/31/2019')
GROUP BY Groups.group_name, CT.Created, CT.Subject_ID
SELECT
CT.Group_Name
, CT.Created
, CS.Topic_Start_Date
, CS.Subject_ID
, P.FirstName
, P.LastName
, CS.Subject_Match_ID
, SubjectX.Firstname AS SubjectX_firstname
, CS.SubjectY
, AEC.AEC AS Max_AEC
, SubjectX.Email_id As SubjectX_Email
, Phone.Phone
, ROW_NUMBER() over(partition by CS.Subject_ID order by CS.Subject_ID) rn
FROM #temp CT
LEFT JOIN QE_Topic_Summary CS ON CS.Subject_ID = CT.Subject_Id
AND (Topic_Status LIKE 'In Progress'
OR Topic_Status LIKE 'Pending')
AND CS.Topic_Start_Date >= DATEADD(Day,-60,CT.Created) AND CS.Topic_Start_Date <= DATEADD(Day,60,CT.Created)
INNER JOIN Subjects P ON P.Subject_ID = CS.Subject_ID
LEFT JOIN Subjects SubjectX ON SubjectX.Subject_ID = CS.SubjectX_ID
LEFT JOIN QE_TB_MAX_AEC AEC ON AEC.Subject_ID = CS.Subject_ID
INNER JOIN Subject_Identifiers PI ON PI.Subject_ID = P.Subject_ID
LEFT JOIN Subject_Identifiers PIP ON PIP.Subject_ID = SubjectX.Subject_ID
LEFT JOIN Subject_Phone Phone On Phone.Subject_ID = P.Subject_ID WHERE Phone.Voice = 1
drop table #temp
I don't see a reference to rn in your WHERE clause, but my guess is that you need to wrap it in another query like so:
SELECT *
FROM(
SELECT
CT.Group_Name
, CT.Created
, CS.Topic_Start_Date
, CS.Subject_ID
, P.FirstName
, P.LastName
, CS.Subject_Match_ID
, SubjectX.Firstname AS SubjectX_firstname
, CS.SubjectY
, AEC.AEC AS Max_AEC
, SubjectX.Email_id As SubjectX_Email
, Phone.Phone
, ROW_NUMBER() over(partition by CS.Subject_ID order by CS.Subject_ID) rn
FROM #temp CT
LEFT JOIN QE_Topic_Summary CS ON CS.Subject_ID = CT.Subject_Id
AND (Topic_Status LIKE 'In Progress'
OR Topic_Status LIKE 'Pending')
AND CS.Topic_Start_Date >= DATEADD(Day,-60,CT.Created) AND CS.Topic_Start_Date <= DATEADD(Day,60,CT.Created)
INNER JOIN Subjects P ON P.Subject_ID = CS.Subject_ID
LEFT JOIN Subjects SubjectX ON SubjectX.Subject_ID = CS.SubjectX_ID
LEFT JOIN QE_TB_MAX_AEC AEC ON AEC.Subject_ID = CS.Subject_ID
INNER JOIN Subject_Identifiers PI ON PI.Subject_ID = P.Subject_ID
LEFT JOIN Subject_Identifiers PIP ON PIP.Subject_ID = SubjectX.Subject_ID
LEFT JOIN Subject_Phone Phone On Phone.Subject_ID = P.Subject_ID
WHERE Phone.Voice = 1
)t
WHERE t.rn = 1
SELECT DISTINCT(t1.Ticker),t2.SecurityID,t2.ClosePrice,t2.QuoteDateTime FROM [Hub].[SecurityMaster].[SecurityMasterDetails] as t1
INNER JOIN [Hub].[SecurityMaster].[SecurityPrices] as t2
ON t2.SecurityID =t1.SecurityID
WHERE t2.QuoteDateTime IN (SELECT max(QuoteDateTime) FROM [Hub].[SecurityMaster].[SecurityPrices]) AND t1.SecurityTypeName = 'REIT'
I get an output with no data. The subquery doesn't run along with the other filter in the WHERE clause. I am not sure what I am doing wrong. Can somebody please help!
If you are trying to get the lastest row from SecurityPrices for each Ticker, one option is to use cross apply():
select --distinct /* distinct not needed if `Ticker` is unique on `smd`
smd.Ticker
, sp.SecurityID
, sp.ClosePrice
, sp.QuoteDateTime
from [Hub].[SecurityMaster].[SecurityMasterDetails] as smd
cross apply (
select top 1
i.SecurityID
, i.ClosePrice
, i.QuoteDateTime
from [Hub].[SecurityMaster].[SecurityPrices] i
where i.SecurityID = smd.SecurityID
order by i.QuoteDateTime desc
) as sp
where SecurityTypeName = 'REIT' /* which table does this column belong to? */
I think your query would be
SELECT DISTINCT TOP 1 WITH TIES
t1.Ticker,
t2.SecurityID,
t2.ClosePrice,
t2.QuoteDateTime
FROM [Hub].[SecurityMaster].[SecurityMasterDetails] as t1
INNER JOIN [Hub].[SecurityMaster].[SecurityPrices] as t2 ON t2.SecurityID =t1.SecurityID
WHERE SecurityTypeName = 'REIT'
ORDER BY t2.QuoteDateTime DESC
You aren't getting results because the max(QuoteDateTime) record doesn't have SecurityTypeName = 'REIT'. I think you want the max(QuoteDateTime) for this SecurityTypeName, so this can be done with an INNER JOIN.
SELECT DISTINCT
(t1.Ticker),
t2.SecurityID,
t2.ClosePrice,
t2.QuoteDateTime
FROM [Hub].[SecurityMaster].[SecurityMasterDetails] as t1
INNER JOIN [Hub].[SecurityMaster].[SecurityPrices] as t2
ON t2.SecurityID =t1.SecurityID
INNER JOIN
(SELECT max(QuoteDateTime) DT FROM [Hub].[SecurityMaster].[SecurityPrices]) P on P.DT = t2.QuoteDateTime
WHERE SecurityTypeName = 'REIT'
EDIT
Your data doesn't have what you think it does, I suspect. Here is how you can check...
--Find the SecurityID that matches the max date
SELECT
SecurityID ,
max(QuoteDateTime) DT
FROM [Hub].[SecurityMaster].[SecurityPrices]
GROUP BY SecurityID
--I'm betting this ID isn't in your SecurityMasterDetails where the Type is REIT
SELECT DISTINCT
SecurityID
FROM SecurityMasterDetails
WHERE SecurityTypeName = 'REIT'
Since the SecurityID returned in the first query isn't in the second query result set, you are going to get NULL results.
Hi can you please take a look why my query is not returning distinct record. i want result with following condition OE1='SCHEDCHNG', need only recent records per orderid or ordernum means only one record per ordernum or orderid and also dropdate is null. My query is as below
select DISTINCT TOP 100 OE.ORDERID,OE.ID,OE.ORDERNUM,OE.OE4 from OrderExports OE
inner join (
select ORDERNUM, max(OE4) as MaxDate
from OrderExports
group by ORDERNUM
) tm
on OE.ORDERNUM = tm.ORDERNUM and OE.OE4 = tm.MaxDate
inner join orde_ O on OE.ORDERID = O.ORDERID
WHERE OE1='SCHEDCHNG' AND O.DROPDATE is null
Pretty sparse on details here but I think you are wanting something along these lines.
with SortedResults as
(
select OE.ORDERID
, OE.ID
, OE.ORDERNUM
, OE.OE4
, ROW_NUMBER() over(partition by OE.ORDERID, OE.ORDERNUM order by OE.OE4 desc) as RowNum
from OrderExports OE
inner join
(
select ORDERNUM
, max(OE4) as MaxDate
from OrderExports
group by ORDERNUM
) tm on OE.ORDERNUM = tm.ORDERNUM and OE.OE4 = tm.MaxDate
inner join orde_ O on OE.ORDERID = O.ORDERID
WHERE OE1='SCHEDCHNG'
AND O.DROPDATE is null
)
select ORDERID
, ID
, ORDERNUM
, OE4
from SortedResults
where RowNum = 1
You can try using max and group by as below :
SELECT a.ID, max(a.ORDERID) as OrderID, max(a.ORDERNUM) as OrderNum,MAX(OE.OE4) as OE4 FROM
(
--your query
) a
group by a.ID
I have a state table which has states assigned to different countries. There are cases where different countries have same state names. How can I get that. I am trying the following query. Am I right.?
SELECT Name , COUNT(*) count
FROM
[DB].[dbo].[State]
GROUP BY
Name
Having
COUNT(*) > 1
Above query gives correct result. But following query is that I am trying to fetch Country Names also. This is not working
SELECT st.Name , COUNT(*) count,co.Name
FROM [DB].[dbo].[State] st
INNER join [DB].[dbo].Country co on st.CountryID = co.ID
GROUP BY
st.Name,
co.Name
Having
COUNT(*) > 1
Yes, that's correct so I don't understand what is the question?
If you want it with the countries name and all the other information you can use EXISTS() :
SELECT * FROM [DB].[dbo].[State] t
WHERE EXISTS(SELECT 1 FROM [DB].[dbo].[State] s
WHERE t.state = s.state and t.country <> s.country)
EDIT: Try this
SELECT st.Name ,co.Name
FROM [DB].[dbo].[State] st
INNER join [DB].[dbo].Country co on st.CountryID = co.ID
WHERE EXISTS(SELECT 1 FROM [DB].[dbo].[State] st2
WHERE st.name = st2.name
HAVING COUNT(*) > 1)
Hope your Query is correct.,
SELECT st.Name,co.Name,COUNT(st.CountryID) [count]
FROM [DB].[dbo].[State] st
LEFT join [DB].[dbo].Country co on st.CountryID = co.ID
GROUP BY
st.Name,co.Name
Having
COUNT(st.CountryID) > 1
SQL Server :
SELECT tblModule.Title , Count (tblActivity.Name) AS NumberOfActivities
From tblActivity
INNER JOIN tblModule
ON tblModule.ModuleID = tblActivity.ModuleID
Order by tblModule.Title
In here I am trying to display the number of times Name is displayed in tblActivity for each Module Title , How would I do this the error is :
Msg 8120, Level 16, State 1, Line 1
Column 'tblModule.Title' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
And the actual question : For each module, list the module title and the number of activities scheduled for the module.(5)
SELECT m.Title, COUNT_BIG(a.Name) AS NumberOfActivities
FROM dbo.tblActivity a
JOIN dbo.tblModule m ON m.ModuleID = a.ModuleID
GROUP BY m.Title
ORDER BY m.Title
or
SELECT m.Title, NumberOfActivities
FROM (
SELECT ModuleID, COUNT_BIG(*) AS NumberOfActivities
FROM dbo.tblActivity
GROUP BY ModuleID
) a
JOIN dbo.tblModule m ON m.ModuleID = a.ModuleID
ORDER BY m.Title
anyway, please provide actual and excepted result...