如何按销售额选择标题,销售额低于N?

时间:2018-01-24 05:54:16

标签: sql sql-server tsql

我有2个表:titlessales由查询创建:

CREATE TABLE [dbo].[sales] 
(
    [stor_id] [char] (4) NOT NULL,
    [ord_num] [varchar] (20) NOT NULL,
    [ord_date] [datetime] NOT NULL, 
    [qty] [smallint] NOT NULL, --quantity of sold books in this transaction
    [payterms] varchar(12) NOT NULL,
    [title_id] varchar(6) NOT NULL, --FOREIGN KEY REFERENCES titles(title_id),

    CONSTRAINT FK_S_title_id 
        FOREIGN KEY (title_id) REFERENCES titles(title_id),
    CONSTRAINT PK_sales 
        PRIMARY KEY CLUSTERED (stor_id, ord_num, title_id)
) ON [PRIMARY]

CREATE TABLE [dbo].[titles] 
(
    [title_id] varchar(6) CONSTRAINT PK_titles PRIMARY KEY CLUSTERED,
    [title] varchar(80) NOT NULL, --name of book
    [type] char(12) NOT NULL DEFAULT ('UNDECIDED'),
    [pub_id] char(4) NULL,
    [price] money NULL,
    [advance] money NULL,
    [royalty] int NULL,
    [ytd_sales] int NULL,
    [notes] varchar(200) NULL,
    [pubdate] datetime NOT NULL DEFAULT (getdate())
) ON [PRIMARY]

我知道我可以通过此查询获得一对titlesumOfSales的表格

SELECT title, SUM(qty) AS sumOfSales 
FROM titles AS t, sales AS s
WHERE t.title_id = s.title_id 
GROUP BY title
ORDER BY title

结果如下:

enter image description here

但是我需要选择销售次数少于或等于10次的所有标题,并且不需要qty(也不是sumOfSales)列来获取此类标题:

title 
=======================================
ABookThatIsSoldLessOrEqual10Times
NameOfAnotherBookSoldLessOrEqual10times
NameOfBookSoldLessOrEqual10times
编辑:谢谢你的回答。我想使用HAVING,但它并不是我在SELECT的结果中所做的事情。我需要列出仅出售10次或更少次的书籍标题。

我可以使用临时表并执行2 SELECT而不是一个。但这不是很好的做法。

3 个答案:

答案 0 :(得分:1)

使用HAVING子句:

SELECT title, SUM(qty) AS sumOfSales
FROM titles AS t, sales AS s
WHERE t.title_id = s.title_id 
GROUP BY title
HAVING SUM(qty) < 11
ORDER BY title

如果您愿意,可以将条件写为SUM(qty) <= 10,但我发现SUM(qty) < 11更优雅。

答案 1 :(得分:1)

您需要在查询中添加HAVING

SELECT title, sum(qty) AS sumOfSales 
FROM 
    titles AS t
    INNER JOIN sales AS s ON t.title_id = s.title_id 
GROUP BY title
HAVING sum(qty) <= 10 
ORDER BY title

答案 2 :(得分:1)

如果你需要显示一本书的标题列表,那么试试这个:

SELECT title FROM titles AS t inner join sale AS s
on t.title_id = s.title_id 
GROUP BY title
HAVING sum(qty) <= 10 
ORDER BY title