我有以下表格:
**Product**
ProdID int
ProdOwner (nvarchar)
Views int
**Reviews**
RevID int
RevDate datetime
ProdOwner
ProdID
如果我将像“Jake Bill”(ProdOwner)这样的字符串传递给我的storedproc,我需要获得以下输出
Total Products Owned: 27
Total Product Views: 78967
Total Reviews Received on All Products: 89
如何编写此查询?我正在使用SQL 2008.这就是我所做的:
CREATE PROCEDURE [dbo].[GetProdCountByOwner]
(
@ProdOwnerName nvarchar(256)
)
AS
SET NOCOUNT ON
SELECT COUNT(p.ProdID), Count(p.Views), Count(r.RevID) FROM Product p join Review r
on p.ProdID = r.ProdID
WHERE p.ProdOwner = @ProdOwnerName
GO
答案 0 :(得分:1)
SELECT COUNT(*) AS [Total Products Owned],
SUM(p.Views) AS [Total Product Views],
(SELECT COUNT(*)
FROM Product p JOIN Reviews r ON p.ProdID = r.ProdID
WHERE p.ProdOwner = 'Jake Bill'
) AS [Total Reviews Received on All Products]
FROM Product p
WHERE p.ProdOwner = 'Jake Bill'
答案 1 :(得分:0)
假设你得到的结果太高(也就是说,所有3个人的得分最高)
SELECT
COUNT(DISTINCT p.ProdID), SUM(p.Views), Count(DISTINCT r.RevID)
FROM
Product p LEFT join Review r on p.ProdID = r.ProdID
WHERE
p.ProdOwner = @ProdOwnerName