house_building.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770
  1. """不动产建筑数据处理
  2. """
  3. # 导入必要的库
  4. import re # 正则表达式库,用于字符串处理
  5. from datetime import datetime # 日期时间库,用于处理日期和时间
  6. from dateutil.relativedelta import relativedelta # 日期时间相对偏移库,用于计算相对日期
  7. from decimal import Decimal # 高精度小数库,用于精确的数值计算
  8. from loguru import logger # 日志库,用于记录日志信息
  9. import pandas as pd # 数据分析库,用于处理数据框
  10. import psycopg # PostgreSQL数据库连接库,用于与PostgreSQL交互
  11. import subprocess
  12. import paramiko
  13. # 配置日志记录器,将日志写入文件a.log
  14. logger.add(sink='a.log')
  15. ssh_hostname = '172.16.107.4' # 定义远程主机地址
  16. ssh_port = 22 # 定义SSH服务的端口号
  17. ssh_username = 'app' # 定义登录远程主机的用户名
  18. ssh_password = '(l4w0ST_' # 定义登录远程主机的密码
  19. # 服务器文件夹路径
  20. remote_dir_path = '/data/history/house/building/'
  21. # 数据库连接信息
  22. db_host = "172.16.107.5" # 数据库主机地址
  23. db_port = 5432 # 数据库端口号
  24. db_username = "finance" # 数据库用户名
  25. db_password = "Finance@unicom23" # 数据库密码
  26. dbname = "financialdb" # 数据库名称
  27. conn_info = f"host='{db_host}' port={db_port} user='{db_username}' password='{db_password}' dbname='{dbname}'"
  28. # 获取当前日期,并计算上个月的第一天
  29. today = datetime.today()
  30. start_date = today - relativedelta(months=1, day=1)
  31. year_month = start_date.strftime('%Y%m')
  32. # 数据文件路径
  33. input_path = 'data.xlsx'
  34. # 输出文件路径
  35. output_path = 'output.csv'
  36. def data_process():
  37. # 初始化全局变量,用于存储组织、区域等映射关系
  38. org_map = {} # 组织ID到组织信息的映射
  39. third_org_list_map = {} # 二级组织ID到其下属三级组织列表的映射
  40. area_map = {} # 区域ID到区域信息的映射
  41. districts_list_map = {} # 城市ID到其下属区县列表的映射
  42. # 连接到PostgreSQL数据库,并获取组织和区域数据
  43. with psycopg.connect(
  44. conninfo=conn_info,
  45. row_factory=psycopg.rows.dict_row
  46. ) as conn:
  47. with conn.cursor() as curs:
  48. # 查询所有一级组织(grade=1)
  49. sql = """
  50. select * from common.organization where grade = 1
  51. """
  52. logger.info(f"sql: {sql}")
  53. curs.execute(sql)
  54. second_orgs = curs.fetchall()
  55. for x in second_orgs:
  56. third_org_list_map[x['id']] = [] # 初始化每个二级组织的三级组织列表为空
  57. # 查询所有组织
  58. sql = """
  59. select * from common.organization
  60. """
  61. logger.info(f"sql: {sql}")
  62. curs.execute(sql)
  63. orgs = curs.fetchall()
  64. for x in orgs:
  65. if x['parent_id'] in third_org_list_map:
  66. third_org_list_map[x['parent_id']].append(x) # 将三级组织添加到对应的二级组织列表中
  67. org_map[x['id']] = x # 构建组织ID到组织信息的映射
  68. # 查询所有省级区域(area_grade=1)
  69. sql = """
  70. select * from common.area where area_grade = 1 order by area_id
  71. """
  72. logger.info(f"sql: {sql}")
  73. curs.execute(sql)
  74. cities = curs.fetchall()
  75. for x in cities:
  76. districts_list_map[x['area_id']] = [] # 初始化每个城市的区县列表为空
  77. # 查询所有区域
  78. sql = """
  79. select * from common.area
  80. """
  81. logger.info(f"sql: {sql}")
  82. curs.execute(sql)
  83. areas = curs.fetchall()
  84. for x in areas:
  85. if x['parent_id'] in districts_list_map:
  86. districts_list_map[x['parent_id']].append(x) # 将区县添加到对应的城市列表中
  87. area_map[x['area_id']] = x # 构建区域ID到区域信息的映射
  88. # 读取Excel文件中的数据并进行预处理
  89. df = pd.read_excel(io=input_path) # 读取Excel文件
  90. df = df.map(lambda x: re.sub(r'\s+', '', x) if type(x) is str else x) # 去除字符串字段中的多余空格
  91. df.drop_duplicates(subset=['建筑ID'], keep='last', inplace=True) # 去重,保留最后一条记录
  92. # 定义函数:根据资产所属单位获取二级组织机构编码
  93. def get_area_no(x):
  94. second_unit = x['资产所属单位(二级)']
  95. third_unit = x['资产所属单位(三级)']
  96. if '河北' == second_unit:
  97. return '-12'
  98. if '长途通信传输局' == second_unit:
  99. return '-11'
  100. if '保定' in second_unit and ('雄县' in third_unit or '容城' in third_unit or '安新' in third_unit):
  101. return '782'
  102. for second_org in second_orgs:
  103. area_name = second_org['name']
  104. area_no = second_org['id']
  105. if area_name in second_unit:
  106. return area_no
  107. raise RuntimeError(f'二级组织机构编码匹配失败: {second_unit}')
  108. df['二级组织机构编码'] = df.apply(get_area_no, axis=1) # 应用函数,生成二级组织机构编码列
  109. # 定义函数:根据二级组织机构编码获取二级组织机构名称
  110. def get_area_name(x):
  111. area_no = x['二级组织机构编码']
  112. second_org = org_map[area_no]
  113. area_name = second_org['name']
  114. return area_name
  115. df['二级组织机构名称'] = df.apply(get_area_name, axis=1) # 应用函数,生成二级组织机构名称列
  116. # 定义函数:根据资产所属单位获取三级组织机构编码
  117. def get_city_no(x):
  118. third_unit = x['资产所属单位(三级)']
  119. area_name = x['二级组织机构名称']
  120. area_no = x['二级组织机构编码']
  121. if area_name == '石家庄':
  122. if '矿区' in third_unit:
  123. return 'D0130185'
  124. if '井陉' in third_unit:
  125. return 'D0130121'
  126. if area_name == '秦皇岛':
  127. if '北戴河新区' in third_unit:
  128. return 'D0130185'
  129. if '北戴河' in third_unit:
  130. return 'D0130304'
  131. if area_name == '唐山':
  132. if '滦县' in third_unit:
  133. return 'D0130223'
  134. if '高新技术开发区' in third_unit:
  135. return 'D0130205'
  136. if area_name == '邢台':
  137. if '内丘' in third_unit:
  138. return 'D0130523'
  139. if '任泽' in third_unit:
  140. return 'D0130526'
  141. if area_name == '邯郸':
  142. if '峰峰' in third_unit:
  143. return 'D0130406'
  144. if area_name == '省机动局':
  145. if '沧州' in third_unit:
  146. return 'HECS180'
  147. if '唐山' in third_unit:
  148. return 'HECS181'
  149. if '秦皇岛' in third_unit:
  150. return 'HECS182'
  151. if '廊坊' in third_unit:
  152. return 'HECS183'
  153. if '张家口' in third_unit:
  154. return 'HECS184'
  155. if '邢台' in third_unit:
  156. return 'HECS185'
  157. if '邯郸' in third_unit:
  158. return 'HECS186'
  159. if '保定' in third_unit:
  160. return 'HECS187'
  161. if '石家庄' in third_unit:
  162. return 'HECS188'
  163. if '承德' in third_unit:
  164. return 'HECS189'
  165. if '衡水' in third_unit:
  166. return 'HECS720'
  167. if '雄安' in third_unit:
  168. return 'HECS728'
  169. return 'HECS018'
  170. if '雄安' == area_name:
  171. third_unit = third_unit.replace('雄安新区', '')
  172. third_org_list = third_org_list_map[area_no]
  173. for third_org in third_org_list:
  174. city_name = third_org['name']
  175. if city_name in third_unit:
  176. return third_org['id']
  177. if '沧州' == area_name:
  178. return 'D0130911'
  179. if '唐山' == area_name:
  180. return 'D0130202'
  181. if '秦皇岛' == area_name:
  182. return 'D0130302'
  183. if '廊坊' == area_name:
  184. return 'D0131000'
  185. if '张家口' == area_name:
  186. return 'D0130701'
  187. if '邢台' == area_name:
  188. return 'D0130502'
  189. if '邯郸' == area_name:
  190. return 'D0130402'
  191. if '保定' == area_name:
  192. return 'D0130601'
  193. if '石家庄' == area_name:
  194. return 'D0130186'
  195. if '承德' == area_name:
  196. return 'D0130801'
  197. if '衡水' == area_name:
  198. return 'D0133001'
  199. if '雄安' == area_name:
  200. return 'D0130830'
  201. return 'HE001'
  202. df['三级组织机构编码'] = df.apply(get_city_no, axis=1) # 应用函数,生成三级组织机构编码列
  203. # 定义函数:根据三级组织机构编码获取三级组织机构名称
  204. def get_city_name(x):
  205. city_no = x['三级组织机构编码']
  206. third_org = org_map[city_no]
  207. city_name = third_org['name']
  208. return city_name
  209. df['三级组织机构名称'] = df.apply(get_city_name, axis=1) # 应用函数,生成三级组织机构名称列
  210. # 定义函数:根据标准地址获取城市ID
  211. def get_city_id(x):
  212. address = x['标准地址']
  213. second_unit = x['资产所属单位(二级)']
  214. third_unit = x['资产所属单位(三级)']
  215. if '雄安' in address or ('保定' in address and ('雄县' in address or '容城' in address or '安新' in address)):
  216. return '133100'
  217. for city in cities:
  218. area_name = city['short_name']
  219. area_id = city['area_id']
  220. if area_name in second_unit:
  221. return area_id
  222. if area_name in third_unit:
  223. return area_id
  224. if area_name in address:
  225. return area_id
  226. return ''
  227. df['city_id'] = df.apply(get_city_id, axis=1) # 应用函数,生成城市ID列
  228. # 定义函数:根据城市ID获取城市名称
  229. def get_city(x):
  230. city_id = x['city_id']
  231. area = area_map.get(city_id)
  232. if pd.notna(area):
  233. city = area['area_name']
  234. return city
  235. return ''
  236. df['city'] = df.apply(get_city, axis=1) # 应用函数,生成城市名称列
  237. # 定义函数:根据标准地址获取区县ID
  238. def get_district_id(x):
  239. address = x['标准地址']
  240. city = x['city']
  241. city_id = x['city_id']
  242. if pd.isna(city) or pd.isna(address):
  243. return ''
  244. if city == '石家庄':
  245. if '矿区' in address:
  246. return '130107'
  247. if '井陉' in address:
  248. return '130121'
  249. if city == '唐山':
  250. if '滦县' in address:
  251. return '130284'
  252. if city == '邢台':
  253. if '内邱' in address:
  254. return '130523'
  255. if '任县' in address:
  256. return '130505'
  257. if city == '雄安':
  258. address = address.replace('雄安新区', '')
  259. districts = districts_list_map.get(city_id)
  260. if not districts:
  261. return ''
  262. for district in districts:
  263. district_name = district['short_name']
  264. if district_name in address:
  265. return district['area_id']
  266. return ''
  267. df['district_id'] = df.apply(get_district_id, axis=1) # 应用函数,生成区县ID列
  268. # 定义函数:根据区县ID获取区县名称
  269. def get_district(x):
  270. district_id = x['district_id']
  271. area = area_map.get(district_id)
  272. if pd.notna(area):
  273. district = area['area_name']
  274. return district
  275. return ''
  276. df['district'] = df.apply(get_district, axis=1) # 应用函数,生成区县名称列
  277. # 定义函数:将百分比字符串转换为小数
  278. def convert_percentage_to_number(x):
  279. if pd.notna(x) and isinstance(x, str) and x.endswith('%'):
  280. return Decimal(x[:-1]) / Decimal('100')
  281. return x
  282. df['得房率'] = df['得房率'].apply(convert_percentage_to_number) # 应用函数,将得房率转换为小数
  283. df['year_no'] = start_date.year # 年份列
  284. df['month_no'] = start_date.month # 月份列
  285. def get_int(x):
  286. try:
  287. return int(x)
  288. except Exception:
  289. return ""
  290. df['房龄开始年份'] = df['房龄开始年份'].apply(get_int)
  291. # 定义函数:计算房龄
  292. def get_house_age(x):
  293. house_year_began = x['房龄开始年份']
  294. if pd.notna(house_year_began) and house_year_began:
  295. current_year = start_date.year
  296. return current_year - house_year_began
  297. return ''
  298. df['house_age'] = df.apply(get_house_age, axis=1) # 应用函数,生成房龄列
  299. df.insert(0, '年月', year_month) # 在数据框第一列插入年月列
  300. # 打印数据框信息
  301. df.info()
  302. # 将结果保存为CSV文件
  303. df.to_csv(
  304. path_or_buf=output_path,
  305. index=False,
  306. header=[
  307. 'year_month', 'first_unit', 'second_unit', 'third_unit', 'building_name', 'inventory_status',
  308. 'inventory_situation', 'modify', 'building_to_be_verified', 'floor_room_to_be_verified', 'building_id',
  309. 'housing_acquisition_rate', 'site_name', 'site_id', 'land_name', 'housing_source', 'acquisition_date',
  310. 'house_year_began', 'investor', 'management_level', 'building_structure', 'total_floors', 'frontage',
  311. 'courtyard', 'whole_building', 'property_ownership_certificate',
  312. 'no_property_ownership_certificate_reason', 'unrelated_assets', 'assets_num', 'assets_tag_num',
  313. 'usage_status', 'building_use', 'ownership_status', 'floor_area', 'building_area',
  314. 'building_area_self_use', 'building_area_rent', 'building_area_idle', 'building_area_unusable',
  315. 'usable_area', 'usable_area_self_use', 'usable_area_rent', 'usable_area_idle', 'usable_area_unusable',
  316. 'community_assistant_name', 'community_assistant_unit', 'lng_jt', 'lat_jt', 'address',
  317. 'property_owner', 'checked', 'area_no', 'area_name', 'city_no', 'city_name', 'city_id', 'city',
  318. 'district_id', 'district', 'year_no', 'month_no', 'house_age'
  319. ],
  320. encoding='utf-8-sig'
  321. )
  322. def data_import():
  323. # 定义 PowerShell 脚本的路径
  324. script_path = r"../../copy.ps1"
  325. # 目标表和文件信息
  326. table = "house.building_month" # 数据库目标表名
  327. # 表字段列名,用于指定导入数据的列顺序
  328. columns = "year_month,first_unit,second_unit,third_unit,building_name,inventory_status,inventory_situation,modify,building_to_be_verified,floor_room_to_be_verified,building_id,housing_acquisition_rate,site_name,site_id,land_name,housing_source,acquisition_date,house_year_began,investor,management_level,building_structure,total_floors,frontage,courtyard,whole_building,property_ownership_certificate,no_property_ownership_certificate_reason,unrelated_assets,assets_num,assets_tag_num,usage_status,building_use,ownership_status,floor_area,building_area,building_area_self_use,building_area_rent,building_area_idle,building_area_unusable,usable_area,usable_area_self_use,usable_area_rent,usable_area_idle,usable_area_unusable,community_assistant_name,community_assistant_unit,lng_jt,lat_jt,address,property_owner,checked,area_no,area_name,city_no,city_name,city_id,city,district_id,district,year_no,month_no,house_age"
  329. # 构造执行 PowerShell 脚本的命令
  330. command = f"powershell -File {script_path} -db_host {db_host} -db_port {db_port} -db_username {db_username} -db_password {db_password} -dbname {dbname} -table {table} -filename {output_path} -columns {columns}"
  331. # 打印生成的命令,方便调试和日志记录
  332. logger.info("command: {}", command)
  333. # 使用 subprocess 模块运行 PowerShell 命令,并捕获输出
  334. completed_process = subprocess.run(
  335. command, # 执行的命令
  336. check=False, # 如果命令执行失败,不抛出异常
  337. text=True, # 将输出作为字符串处理
  338. capture_output=True, # 捕获标准输出和标准错误
  339. )
  340. # 打印命令执行的结果,包括返回码、标准输出和标准错误
  341. logger.info("导入结果:\n{}\n{}\n{}", completed_process.returncode, completed_process.stdout,
  342. completed_process.stderr)
  343. # 定义正则表达式,用于匹配标准输出中的 COPY 结果
  344. p = re.compile(r"^(COPY) (\d+)$")
  345. count = None # 初始化计数变量
  346. matcher = p.match(completed_process.stdout) # 匹配标准输出中的 COPY 结果
  347. if matcher:
  348. count = int(matcher.group(2)) # 提取导入的数据行数
  349. # 如果没有成功提取到导入数据的行数,抛出运行时异常
  350. if count is None:
  351. raise RuntimeError("导入数据失败")
  352. def upload_file():
  353. remote_path = f'{remote_dir_path}{year_month}.xlsx' # 定义远程主机的目标文件路径
  354. # 使用paramiko.SSHClient创建一个SSH客户端对象,并通过with语句管理其上下文
  355. with paramiko.SSHClient() as ssh:
  356. # 设置自动添加主机密钥策略,避免因未知主机密钥导致连接失败
  357. ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  358. # 连接到远程主机,传入主机地址、端口、用户名和密码
  359. ssh.connect(ssh_hostname, port=ssh_port, username=ssh_username, password=ssh_password)
  360. # 执行远程命令,创建远程目录(如果不存在)
  361. ssh.exec_command(f'mkdir -p {remote_dir_path}')
  362. # 打开SFTP会话,用于文件传输,并通过with语句管理其上下文
  363. with ssh.open_sftp() as sftp:
  364. # 记录日志,提示即将上传的本地文件和远程目标路径
  365. logger.info("upload {} to {}", input_path, remote_path)
  366. # 使用SFTP的put方法将本地文件上传到远程主机
  367. sftp.put(input_path, remote_path)
  368. # 记录日志,提示文件已成功上传
  369. logger.info("uploaded {}", input_path)
  370. def data_update():
  371. with psycopg.connect(
  372. conninfo=conn_info,
  373. ) as conn:
  374. with conn.cursor() as curs:
  375. # 更新局址信息
  376. sql = f"""
  377. update
  378. house.building_month a
  379. set
  380. site_num = b.site_num,
  381. city_level = b.city_level,
  382. city_region = b.city_region,
  383. area_sector = b.area_sector,
  384. has_land = b.has_land
  385. from
  386. house.site_month b
  387. where
  388. a.site_id = b.site_id
  389. and a.year_month = b.year_month
  390. and a.year_month = {year_month}
  391. """
  392. logger.info(f"sql: {sql}")
  393. curs.execute(sql)
  394. logger.info(f"update {curs.rowcount}")
  395. # 更新经纬度
  396. sql = f"""
  397. with
  398. t101 as (
  399. select
  400. *
  401. from
  402. house.building_month
  403. where
  404. year_month = 202312
  405. )
  406. update
  407. house.building_month a
  408. set
  409. lng_wgs84 = b.lng_wgs84,
  410. lat_wgs84 = b.lat_wgs84,
  411. lng_bd09 = b.lng_bd09,
  412. lat_bd09 = b.lat_bd09,
  413. building_img = b.building_img
  414. from
  415. t101 b
  416. where
  417. a.year_month = {year_month}
  418. and a.building_id = b.building_id
  419. """
  420. logger.info(f"sql: {sql}")
  421. curs.execute(sql)
  422. logger.info(f"update {curs.rowcount}")
  423. # 更新闲置建筑面积超过1000平米策略
  424. sql = f"""
  425. insert
  426. into
  427. house.building_idle_strategy
  428. (
  429. year_month,
  430. building_id,
  431. first_unit,
  432. second_unit,
  433. third_unit,
  434. site_num,
  435. site_name,
  436. address,
  437. city_level,
  438. city_region,
  439. area_sector,
  440. has_land,
  441. site_id,
  442. building_name,
  443. housing_acquisition_rate,
  444. housing_source,
  445. acquisition_date,
  446. house_year_began,
  447. investor,
  448. management_level,
  449. building_structure,
  450. total_floors,
  451. assets_num,
  452. assets_tag_num,
  453. usage_status,
  454. building_use,
  455. ownership_status,
  456. floor_area,
  457. building_area,
  458. building_area_self_use,
  459. building_area_rent,
  460. building_area_idle,
  461. building_area_unusable,
  462. usable_area,
  463. usable_area_self_use,
  464. usable_area_rent,
  465. usable_area_idle,
  466. usable_area_unusable,
  467. city,
  468. district,
  469. lng_wgs84,
  470. lat_wgs84,
  471. lng_bd09,
  472. lat_bd09,
  473. building_img,
  474. area_no,
  475. area_name,
  476. city_no,
  477. city_name,
  478. year_no,
  479. month_no,
  480. house_age,
  481. land_name,
  482. frontage,
  483. courtyard,
  484. whole_building,
  485. property_ownership_certificate,
  486. no_property_ownership_certificate_reason,
  487. unrelated_assets,
  488. community_assistant_name,
  489. community_assistant_unit,
  490. lng_jt,
  491. lat_jt,
  492. property_owner,
  493. checked,
  494. city_id,
  495. district_id
  496. )
  497. select
  498. year_month,
  499. building_id,
  500. first_unit,
  501. second_unit,
  502. third_unit,
  503. site_num,
  504. site_name,
  505. address,
  506. city_level,
  507. city_region,
  508. area_sector,
  509. has_land,
  510. site_id,
  511. building_name,
  512. housing_acquisition_rate,
  513. housing_source,
  514. acquisition_date,
  515. house_year_began,
  516. investor,
  517. management_level,
  518. building_structure,
  519. total_floors,
  520. assets_num,
  521. assets_tag_num,
  522. usage_status,
  523. building_use,
  524. ownership_status,
  525. floor_area,
  526. building_area,
  527. building_area_self_use,
  528. building_area_rent,
  529. building_area_idle,
  530. building_area_unusable,
  531. usable_area,
  532. usable_area_self_use,
  533. usable_area_rent,
  534. usable_area_idle,
  535. usable_area_unusable,
  536. city,
  537. district,
  538. lng_wgs84,
  539. lat_wgs84,
  540. lng_bd09,
  541. lat_bd09,
  542. building_img,
  543. area_no,
  544. area_name,
  545. city_no,
  546. city_name,
  547. year_no,
  548. month_no,
  549. house_age,
  550. land_name,
  551. frontage,
  552. courtyard,
  553. whole_building,
  554. property_ownership_certificate,
  555. no_property_ownership_certificate_reason,
  556. unrelated_assets,
  557. community_assistant_name,
  558. community_assistant_unit,
  559. lng_jt,
  560. lat_jt,
  561. property_owner,
  562. checked,
  563. city_id,
  564. district_id
  565. from
  566. house.building_month
  567. where
  568. building_area_idle > 1000
  569. and year_month = {year_month}
  570. order by
  571. building_area_idle desc
  572. """
  573. logger.info(f"sql: {sql}")
  574. curs.execute(sql)
  575. logger.info(f"update {curs.rowcount}")
  576. sql = f"""
  577. with
  578. t101 as (
  579. select
  580. *,
  581. row_number() over (
  582. order by building_area_idle desc) as sort
  583. from
  584. house.building_idle_strategy
  585. where
  586. year_month = {year_month}
  587. ),
  588. t201 as (
  589. select
  590. area_no,
  591. area_name,
  592. city_no,
  593. city_name,
  594. 'kpi_301320_155_01' as kpi_code,
  595. '闲置建筑面积' as kpi_name,
  596. round(building_area_idle, 2)::varchar as kpi_value,
  597. '1' as kpi_type,
  598. building_id as jk_object_no,
  599. building_name as jk_object,
  600. sort
  601. from
  602. t101
  603. ),
  604. t202 as (
  605. select
  606. area_no,
  607. area_name,
  608. city_no,
  609. city_name,
  610. 'kpi_301320_155_02' as kpi_code,
  611. '房产名称' as kpi_name,
  612. building_name as kpi_value,
  613. '0' as kpi_type,
  614. building_id as jk_object_no,
  615. building_name as jk_object,
  616. sort
  617. from
  618. t101
  619. ),
  620. t203 as (
  621. select
  622. area_no,
  623. area_name,
  624. city_no,
  625. city_name,
  626. 'kpi_301320_155_03' as kpi_code,
  627. '房产编号' as kpi_name,
  628. building_id as kpi_value,
  629. '0' as kpi_type,
  630. building_id as jk_object_no,
  631. building_name as jk_object,
  632. sort
  633. from
  634. t101
  635. ),
  636. t204 as (
  637. select
  638. area_no,
  639. area_name,
  640. city_no,
  641. city_name,
  642. 'kpi_301320_155_04' as kpi_code,
  643. '房产总建筑面积' as kpi_name,
  644. round(building_area, 2)::varchar as kpi_value,
  645. '0' as kpi_type,
  646. building_id as jk_object_no,
  647. building_name as jk_object,
  648. sort
  649. from
  650. t101
  651. ),
  652. t301 as (
  653. select
  654. *
  655. from
  656. t201
  657. union all
  658. select
  659. *
  660. from
  661. t202
  662. union all
  663. select
  664. *
  665. from
  666. t203
  667. union all
  668. select
  669. *
  670. from
  671. t204
  672. )
  673. insert
  674. into
  675. publish.house_building_idle_strategy
  676. (
  677. acct_date,
  678. dept_code,
  679. dept_name,
  680. strategy_code,
  681. area_no,
  682. area_name,
  683. city_no,
  684. city_name,
  685. sale_no,
  686. sale_name,
  687. jk_object_no,
  688. jk_object,
  689. kpi_code,
  690. kpi_name,
  691. kpi_value,
  692. kpi_type,
  693. sort
  694. )
  695. select
  696. {year_month} as acct_date,
  697. '301320' as dept_code,
  698. '河北省分公司纵横运营中心' as dept_name,
  699. '301320_155' as strategy_code,
  700. area_no,
  701. area_name,
  702. city_no,
  703. city_name,
  704. '' as sale_no,
  705. '' as sale_name,
  706. jk_object_no,
  707. jk_object,
  708. kpi_code,
  709. kpi_name,
  710. kpi_value,
  711. kpi_type,
  712. sort
  713. from
  714. t301
  715. order by
  716. sort,
  717. kpi_code
  718. """
  719. logger.info(f"sql: {sql}")
  720. curs.execute(sql)
  721. logger.info(f"update {curs.rowcount}")
  722. data_process()
  723. data_import()
  724. upload_file()
  725. data_update()