我有一张表:
+====+========+========+
| Id | name | value |
+====+========+========+
| 1 | a | 7 |
+----+--------+--------+
| 2 | c | 7 |
+----+--------+--------+
| 1 | g | 1 |
+----+--------+--------+
| 2 | c | 2 |
+----+--------+--------+
| 4 | g | 5 |
+----+--------+--------+
| 6 | t | 4 |
+----+--------+--------+
根据以下两个条件,我需要编写两(2)个查询来生成两个报告:
报告Output1 =如果id和name相同(id,name,val) 报告Output2 =如果id相同但名称不同(id,name,val)
如何编写这两个查询?
答案 0 :(得分:0)
你的条件不明确,但mybe就是你想要的:
container
如果您希望在一个结果中同时显示两个查询的结果,则可以使用DECLARE @T TABLE (Id INT, Name VARCHAR(25), Value INT);
DECLARE @YourId INT = 1;
DECLARE @YourName VARCHAR(25) ='a';
/**/
INSERT INTO @T VALUES
(1, 'a', 7),
(2, 'c', 7),
(1, 'g', 1),
(2, 'c', 2),
(4, 'g', 5),
(6, 't', 4);
/*First query*/
SELECT *
FROM @T
WHERE ID = @YourID AND Name = @YourName;
/*Second query*/
SELECT *
FROM @T
WHERE ID = @YourID;
作为:
UNION ALL
<强> Demo 强>
答案 1 :(得分:0)
嗯,我不确定,OP想要什么,但也许是这样的?
// records where id and value are the same
SELECT * FROM @T WHERE ID=Value;
// other records having the same ids as abobe, but DIFFERENT values
SELECT * FROM @T WHERE ID IN
(SELECT ID FROM @T WHERE ID=Value)
AND Id!=Value;
结果:
Id Name Value
1 g 1
2 c 2
Id Name Value
1 a 7
2 c 7
感谢@Sami提供我修改为DEMO的小提琴。