简体   繁体   中英

Adventure Works SQL Server Enquiry

I am writing a SQL query using the AdventureWorks 2014 database.

I want to show Which orders contain more than two products? Show order number, order value, and number of products that the order contains.

I tried to write statement by itself (see below), but I'd like to be able to solve the relation :

select SalesOrderID , ProductID , LineTotal
from Sales.SalesOrderDetail
order by SalesOrderID

在此处输入图片说明

@Juan Carlos Oropeza

i did it can you check if there is something wrong with it

select  s.SalesOrderID,
        a.SalesOrderCount, 
        a.ProductCount,
        sum(LineTotal) as OrderValue 
from  Sales.SalesOrderDetail s , 
      (select SalesOrderID ,
              count(SalesOrderID)  as SalesOrderCount ,
              count(productid) as ProductCount
       from Sales.SalesOrderDetail
       group by SalesOrderID 
      ) a
where s.SalesOrderID = a.SalesOrderID
group by a.salesordercount, s.SalesOrderID, a.ProductCount
having a.ProductCount >2 
order by s.SalesOrderID
SELECT SalesOrderID,
       COUNT(ProductID) as total_products,
       SUM(LineTotal) as total_invoice
FROM SalesOrderDetail s
GROUP BY SalesOrderID
HAVING COUNT(ProductID) > 2
ORDER BY s.SalesOrderID
Select 
    SalesOrderID, 
    sum(LineTotal) as [order value], 
    count(SalesOrderID) as [number of Product] 
from Sales.SalesOrderDetail 
    group by SalesOrderID having count(SalesOrderID)>=2 
    order by SalesOrderID desc

This code would give your expected answer

SELECT SalesOrderID 
        ,ProductID
        ,LineTotal
        ,'Sales Order ' +CAST(SalesOrderID AS VARCHAR(100))+'  Contains Productid of'+CAST(ProductID  AS VARCHAR(100))
        AS [ProductsCountPerOrder] 
       ,Productscount
    FROM
(
SELECT   salesorderid , 
         productid , 
         linetotal , 
         Count(productid)OVER(partition BY salesorderid ORDER BY salesorderid) AS productscount 
FROM     sales.salesorderdetail 
)dt 
WHERE dt.productscount>2 
ORDER BY salesorderid

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM