使用SQL Server,我不是DBA,但我可以编写一些通用SQL。现在已经把头发拉了大约一个小时。搜索我找到了几个解决方案,但由于GROUP BY的工作方式,它们都失败了。
我有一个包含两列的表格,我试图检查重复项:
我正在寻找具有重复userid
和orderdate
的行。我想显示这些行。
如果我使用group by,我无法提取任何其他数据,例如订单ID,因为它不在group by子句中。
答案 0 :(得分:4)
您可以在子查询中使用分组查询:
function splitAllTest(){
var ss=SpreadsheetApp.getActiveSpreadsheet();
var s=ss.getSheetByName("Réponses au formulaire 1");
var lr=s.getLastRow();
var lc=s.getLastColumn()-8; //data columns num
var range=s.getRange(1, 3, lr, lc).getValues()
var output=[];
var split=[];
var l = 0; // outout row count
for(var i=0;i<range.length;i++){ //row roop
// split column_data
var split = [];
var max1 = 0;
for(var j=0;j<range[0].length;j++){ // column roop
var colSplit = range[i][j].split(", ");
split[j] = colSplit;
if(max1 < split[j].length) max1 = split[j].length;
}
// push new rows data
for(var k=0;k<max1;k++){ // max1
output [l] = [];
for(var j=0;j<lc;j++){ // column
if(k < split[j].length) { // if length is 1 k is only 0
output[l].push(split[j][k]); // split [col_index][coldata_index]
}else{
//output[l].push(''); change 2017/03/08 takashi
output[l].push(j == 0 ? split[j][0]: ''); //only first name is filled on each associated line
}}
l++;
}}
ss.getSheetByName("Temp formulaire").clear().getRange(1, 2,
output.length,lc).setValues(output);
}
答案 1 :(得分:1)
您还可以使用窗口函数:
; With CTE as
(Select *
, count(*) over (partition by UserID, OrderDate) as DupRows
from MyTable)
Select *
from CTE
where DupRows > 1
order by UserID, OrderDate
答案 2 :(得分:0)
您可以使用groupby和having获取重复项。像这样:
SELECT
userid,orderdate, COUNT(*)
FROM
yourTable
GROUP BY
userid,orderdate
HAVING
COUNT(*) > 1
编辑:
SELECT * FROM yourTable
WHERE CONCAT(userid,orderdate) IN
(
SELECT
CONCAT(userid,orderdate)
FROM
yourTable
GROUP BY
userid,orderdate
HAVING
COUNT(*) > 1
)
答案 3 :(得分:0)
SELECT *
FROM myTable
WHERE CAST(userid as Varchar) + '/' + CONVERT(varchar(10),orderdate,103) In
(
SELECT
CAST(userid as Varchar) + '/' + CONVERT(varchar(10),orderdate,103)
FROM myTable
GROUP BY userid , orderdate
HAVING COUNT(*) > 1
);