从给定的参考表数据中找出商店名称,可在所有城市中找到

时间:2017-10-15 10:37:28

标签: sql-server

示例数据:

+----+----------+-----------+
| Id | CityName | StoreName |
+----+----------+-----------+
|  1 | Delhi    | A         |
|  2 | Goa      | C         |
|  3 | Delhi    | C         |
|  4 | Pune     | A         |
|  5 | Pune     | B         |
|  6 | Pune     | C         |
+----+----------+-----------+

预期结果:

+----------+-----------+
| CityName | StoreName |
+----------+-----------+
| Delhi    | C         |
| Goa      | C         |
| Pune     | C         |
+----------+-----------+

2 个答案:

答案 0 :(得分:0)

您需要使用MAX()GROUP BY

DECLARE @T TABLE (Id INT, CityName VARCHAR(50), StoreName CHAR(1) );

INSERT INTO @T VALUES
(1, 'Delhi', 'A' ),         
(2, 'Goa', 'C' ),         
(3, 'Delhi', 'C' ),         
(4, 'Pune', 'A' ),         
(5, 'Pune', 'B' ),         
(6, 'Pune', 'C' );

    SELECT CityName, Max(StoreName) As StoreName
    FROM @T
    GROUP BY CityName;

结果:

+==========+===========+
| CityName | StoreName |
+==========+===========+
| Delhi    | C         |
+----------+-----------+
| Goa      | C         |
+----------+-----------+
| Pune     | C         |
+----------+-----------+

答案 1 :(得分:0)

不确定我是否理解你留给萨米的评论。但是,如果您希望storenames等于b

,则可以执行此操作
DECLARE @T TABLE (Id INT, CityName VARCHAR(50), StoreName CHAR(1) ); INSERT INTO @T VALUES (1, 'Delhi', 'A' ), (2, 'Goa', 'B' ), (3, 'Delhi','B'), (4, 'Delhi', 'C' ), (5, 'Pune', 'A' ), (6, 'Pune', 'B' ), (7, 'Pune', 'C' );

select cityname, storename from @t
where storename = 'b'
group by storename, cityname

回答您的原始问题,您可以使用萨米所做的或:

select cityname, storename from @t
where storename = 'c'
group by storename, cityname

如果双方均未回答您的问题,请发布新问题或使用适当的业务规则和所需结果更新您的问题。但这看起来是sql基础知识,试着查看TheGameiswar留给你的链接。