将Excel表重新格式化为更友好的SQL结构

我有一张非常宽的Excel表格,来自A列DIE(约2500列宽)的调查数据。 每一列都是一个问题,每一行都是一个回应。 我试图将数据上传到SQL,并使用UNPIVOT函数将其转换为更适合SQL的格式,但是我甚至无法将其加载到SQL中,因为它超过了1024列的限制。

基本上,我有一个Excel工作表,如下所示:

在这里输入图像说明

但是我想把它转换成这样的样子:

在这里输入图像说明

在Excel(上传之前)或SQL(避开1024列限制)的情况下,我可以做什么样的select?

我不得不这样做。 我的解决scheme是编写一个Python脚本,该脚本将会parsingCSV文件(通常从Excel中导出),创build另一个CSV文件。 Python代码在这里: https : //pypi.python.org/pypi/un-xtab/和文档在这里: http : //pythonhosted.org/un-xtab/ 。 我从来没有在2500列的文件上运行它,但不知道为什么它不起作用。

R在其中一个库中有一个非常特殊的函数调用。 您还可以用R连接,读取和写入数据到数据库中。 build议下载R和Rstudio。

这是一个工作脚本,让你开始做你所需要的:

样本数据:

df <- data.frame(id = c(1,2,3), question_1 = c(1,0,1), question_2 = c(2,0,2)) df 

input表格:

  id question_1 question_2 1 1 1 2 2 2 0 0 3 3 1 2 

代码转置数据:

 df2 <- gather(df, key = id, value = values) df2 

输出:

  id id values 1 1 question_1 1 2 2 question_1 0 3 3 question_1 1 4 1 question_2 2 5 2 question_2 0 6 3 question_2 2 

一些辅助函数可供您导入和导出csv数据:

 # Install and load the necessary libraries install.packages(c('tidyr','readr')) library(tidyr) library(readr) # to read a csv file df <- read_csv('[some directory][some filename].csv') # To output the csv file write.csv(df2, '[some directory]data.csv', row.names = FALSE) 

感谢所有的帮助。 由于SQL(超过1024列)和Excel(输出超过100万行)的限制,我最终使用Python。 我从rd_nielson的代码中借用了这些概念,但是这比我所需要的要复杂一些。 如果对其他人有帮助,这是我使用的代码。 它输出一个csv文件,3列,1400万行,我可以上传到SQL。

 import csv with open('Responses.csv') as f: reader = csv.reader(f) headers = next(reader) # capture current field headers newHeaders = ['ResponseID','Question','Response'] # establish new header names with open('PythonOut.csv','w') as outputfile: writer=csv.writer(outputfile, dialect='excel', lineterminator='\n') writer.writerow(newHeaders) # write new headers to output QuestionHeaders = headers[1:len(headers)] # Slice the question headers from original header list for row in reader: questionCount = 0 # start counter to loop through each question (column) for every response (row) while questionCount <= len(QuestionHeaders) - 1: newRow = [row[0], QuestionHeaders[questionCount], row[questionCount + 1]] writer.writerow(newRow) questionCount += 1