如何将datediff与具有count的语句一起使用

时间:2018-10-09 09:13:53

标签: sql-server

如果该特定商品已被售出2次以上,我试图获取两件商品之间的时间间隔,然后我将如何在以后将其用于别名bybytime?

但我收到此错误:

  

列'sales.InvoiceDetailItem.DateTimeCreated'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。   消息8120,第16级,状态1,第4行   在选择列表中,“ file.Item.DateTimeCreated”列无效,因为它既不包含在聚合函数中,也不包含在GROUP BY子句中。

    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]

2 个答案:

答案 0 :(得分:1)

我想你想要这样的东西:

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];

答案 1 :(得分:1)

您可以选择count(PS。[ItemCode]) 为什么使用“ *”?

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]