数据库
首页 > 数据库> > SQL-几个面试题

SQL-几个面试题

作者:互联网

原文链接:http://www.cnblogs.com/LifeDecidesHappiness/p/9339765.html
/*
    人员:LDH
    功能:SQL-几个面试题
    日期:2018-7-20
 */

USE TestDB;
GO

DECLARE @t TABLE
(
    BuyPerson NVARCHAR(20) NOT NULL,
    ProductName NVARCHAR(20) NOT NULL,
    Amount INT NOT NULL
        DEFAULT 0
);

INSERT INTO @t
(   BuyPerson,
    ProductName,
    Amount
)
VALUES
( N'A', N'甲', 2),
( N'B', N'乙', 4),
( N'C', N'丙', 1),
( N'A', N'丁', 2),
( N'B', N'丙', 6);

SELECT BuyPerson,
    ProductName,
    Amount
FROM @t;

-- 查询出所有购入商品为两种或两种以上的购物记录
SELECT BuyPerson,
    COUNT(ProductName) AS '商品种类数'
FROM @t
GROUP BY BuyPerson
HAVING COUNT(ProductName) > = 2;

WITH info(BuyPerson, ProductName, CategoryCount)
AS (SELECT BuyPerson,
        ProductName,
        COUNT(ProductName) OVER (PARTITION BY BuyPerson) AS CategoryCount
    FROM @t
   )
SELECT info.BuyPerson,
    info.ProductName,
    info.CategoryCount
FROM info
WHERE info.CategoryCount > = 2;

DECLARE @Product TABLE
(
    Name NVARCHAR(20) NOT NULL,
    ProductAddress NVARCHAR(10) NOT NULL,
    ProductPrice FLOAT NOT NULL
        DEFAULT 0
);
INSERT INTO @Product
(   Name,
    ProductAddress,
    ProductPrice
)
VALUES
( N'苹果', N'山东', 2.5),
( N'苹果', N'云南', 1.9),
( N'苹果', N'四川', 3),
( N'西瓜', N'江西', 1.5),
( N'西瓜', N'北京', 2.4);

SELECT Name,
    ProductAddress,
    ProductPrice
FROM @Product;

-- 查询平均价格在2元以下的商品名称
SELECT Name,
    AVG(ProductPrice) AS '平均价格'
FROM @Product
GROUP BY Name
HAVING AVG(ProductPrice) < 2;

WITH it(Name, AvgPrice)
AS (SELECT Name,
        AvgPrice = AVG(ProductPrice) OVER (PARTITION BY Name)
    FROM @Product
   )
SELECT it.Name,
    it.AvgPrice
FROM it
WHERE it.AvgPrice < 2
GROUP BY it.Name,
    it.AvgPrice;

WITH t(Name, AvgPrice)
AS (SELECT Name,
        AvgPrice = AVG(ProductPrice) OVER (PARTITION BY Name)
    FROM @Product
   )
SELECT DISTINCT t.Name,
    t.AvgPrice
FROM t
WHERE t.AvgPrice < 2;

 

转载于:https://www.cnblogs.com/LifeDecidesHappiness/p/9339765.html

标签:面试题,ProductPrice,Name,几个,AvgPrice,BuyPerson,SQL,ProductName,SELECT
来源: https://blog.csdn.net/weixin_30302609/article/details/96731513