beayancan
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # IIC2713 Tarea 2 ## Comandos útiles ### Manejo del sistema Para entrar a la consola de postgres: ```bash= sudo -u postgres psql ``` Para crear el database (dentro de psql): ```sql= create database sistemasinfo; ``` Para ver los databases ```sql= \l ``` Para borrar un database: ```sql= drop database <nombre>; ``` Para conectarse (entrar) al database creado: ```sql= \c sistemasinfo; ``` Para ver las tablas creadas en la database: * `\d` (se ven todas) * `\d <nombre_detabla>` (se ve como se compone esa tabla) Para más comandos [sigue el siguiente link](https://stackoverflow.com/questions/769683/show-tables-in-postgresql) ### Fecha Postgres por defecto tiene yyyy%mm%dd para cambiarlo a dd%mm%yyyy: * Hacer pruebas de consulta de fecha antes de usar este comando, a veces no es necesario ```sql= SET datestyle = "ISO, DMY"; ``` ## Importar Tablas #### Adquisiciones *probado* ```sql CREATE TABLE adquisiciones(EAN bigint, id_proveedor int, cantidad int, fecha_adquisicion date); \COPY adquisiciones(EAN, id_proveedor, cantidad, fecha_adquisicion) FROM 'adquisiciones.csv' delimiter ',' csv header; SELECT * FROM adquisiciones; ``` #### Clientes *probado* ```sql CREATE TABLE clientes(id_cliente int, nombre varchar(30), rut varchar(30), dir_calle varchar(50), telefono_empresa bigint, web varchar(60), contacto_ventas varchar(60), telefono_contacto bigint, correo varchar(60), cargo varchar(20)); \COPY clientes(id_cliente, nombre, rut, dir_calle, telefono_empresa, web, contacto_ventas, telefono_contacto, correo, cargo) FROM 'clientes.csv' delimiter ',' csv header; ``` *probado* ```sql CREATE TABLE clientes(id_cliente int, nombre varchar(30), rut varchar(30), dir_calle varchar(50), telefono_empresa bigint, web varchar(60), contacto_ventas varchar(60), telefono_contacto bigint, correo varchar(60), cargo varchar(20)); \COPY clientes(id_cliente, nombre, rut, dir_calle, telefono_empresa, web, contacto_ventas, telefono_contacto, correo, cargo) FROM 'clientes.csv' delimiter ',' csv header; ``` #### Cobranzas Nuevas * Será la única tabla cuyas fechas sean `varchar`, por lo que es la única tabla que necesita casteo *probado* ```sql CREATE TABLE cobranzas(id_factura int, fecha_pago varchar(30)); \COPY cobranzas(id_factura, fecha_pago) FROM 'cobranzas.csv' delimiter ',' csv header; SELECT * FROM cobranzas; ``` * Ejemplo consulta de rango de fecha usando casteo, el orden debe respetarse ```sql SELECT * FROM COBRANZAS WHERE ( fecha_pago <> 'No pagado') AND ( fecha_pago::date >= '01/01/2020' ) AND ( fecha_pago::date <= '31/01/2020' ); ``` #### Despachos *probado* ```sql CREATE TABLE despachos(id_pedido int, fecha_despacho date, cantidad_despachada int); \COPY despachos(id_pedido, fecha_despacho, cantidad_despachada) FROM 'despachos.csv' delimiter ',' csv header; SELECT * FROM despachos; ``` #### Facturas *probado* ```sql CREATE TABLE facturas(id_pedido int, id_factura int, fecha_facturacion date, total_facturado float); \COPY facturas(id_pedido, id_factura, fecha_facturacion, total_facturado) FROM 'facturas.csv' delimiter ',' csv header; SELECT * FROM facturas; ``` #### Pedidos *probado* ```sql CREATE TABLE pedidos(id_pedido int, fecha_pedido date, EAN bigint, cantidad_solicitada int, id_vendedor int,id_cliente int, precio_real int); \COPY pedidos(id_pedido, fecha_pedido, EAN, cantidad_solicitada, id_vendedor, id_cliente, precio_real) FROM 'pedidos.csv' delimiter ',' csv header; SELECT * FROM pedidos; ``` #### Productos *probado* ```sql CREATE TABLE productos(EAN bigint, nombre varchar(100), categoria varchar(100), costo int, precio_recomendado int, saldo int, id_proveedor int); \COPY productos(EAN, nombre, categoria, costo, precio_recomendado, saldo, id_proveedor) FROM 'productos.csv' delimiter ',' csv header; SELECT * FROM productos; ``` #### Proveedores *probado* ```sql CREATE TABLE proveedores(id_proveedor int, nombre varchar(30)); \COPY proveedores(id_proveedor, nombre) FROM 'proveedores.csv' delimiter ',' csv header; SELECT * FROM proveedores; ``` #### Vendedores *probado* ```sql CREATE TABLE vendedores(id_vendedor int, apellido varchar(20), nombre varchar(20)); \COPY vendedores(id_vendedor, apellido, nombre) FROM 'vendedores.csv' delimiter ',' csv header; SELECT * FROM vendedores; ``` ## Consultas ##### a) Determine cuántas unidades de cada categoría de productos fueron adquiridas durante el año 2019. Entregue nombre de categoría y número de unidades adquiridas ¿Cuáles fueron las categorías con mayor y menor número de unidades adquiridas? ```sql SELECT PROD.categoria AS categoria, sum(ADQ.cantidad) AS unidades FROM ADQUISICIONES AS ADQ, PRODUCTOS AS PROD WHERE (ADQ.ean = PROD.ean) AND (ADQ.fecha_adquisicion >= '01/01/2019') AND (ADQ.fecha_adquisicion <= '31/12/2019') GROUP BY PROD.categoria ORDER BY unidades DESC; ``` ##### b) ¿Cuáles son los 5 productos con menor facturación (en pesos) del año 2019? Entregue su EAN, nombre y suma de las facturaciones. *sin joins con where solamente* ```sql SELECT PROD.ean, PROD.nombre, sum(FAC.total_facturado) AS facturado FROM PRODUCTOS AS PROD, FACTURAS AS FAC, PEDIDOS AS PED WHERE (FAC.id_pedido = PED.id_pedido) AND (PED.ean = PROD.ean) AND (FAC.fecha_facturacion >= '01/01/2019') AND (FAC.fecha_facturacion <= '31/12/2019') GROUP BY (PROD.ean, PROD.nombre) ORDER BY facturado ASC LIMIT 5; ``` *con joins* ```sql SELECT PRODUCTOS.ean, nombre, sum(FACTURAS.total_facturado) AS facturado FROM FACTURAS JOIN PEDIDOS ON (PEDIDOS.id_pedido = FACTURAS.id_pedido) JOIN PRODUCTOS ON (PEDIDOS.ean) = (PRODUCTOS.ean) WHERE (FACTURAS.fecha_facturacion >= '01/01/2019') AND (FAC.fecha_facturacion <= '31/12/2019') GROUP BY (PRODUCTOS.ean, PRODUCTOS.nombre) ORDER BY facturado ASC LIMIT 5; ``` ##### c) Determine la cantidad inicial de inventario de los productos al comienzo del 2020. Entregue nombre del producto, EAN y cantidad inicial. (Asuma que es el mismo saldo de inventario del 31-12-2019 ) ```sql SELECT PROD.nombre, PROD.ean, sum(PROD.saldo) + sum(ADQ.cantidad) AS cantidad_inicial FROM PRODUCTOS AS PROD, ADQUISICIONES AS ADQ WHERE (PROD.ean = ADQ.ean) AND (ADQ.fecha_adquisicion <= '31/12/2019') GROUP BY (PROD.nombre, PROD.ean) ORDER BY cantidad_inicial DESC; ``` ##### d) Determine los pedidos en los que la cantidad solicitada es mayor o igual a 45. Entregue No pedido, EAN, nombre producto, cantidad solicitada y cliente. ```sql SELECT PED.id_pedido AS num_pedido, PROD.ean, PROD.nombre AS nombre_producto, PED.cantidad_solicitada, CL.nombre AS nombre_cliente FROM PEDIDOS AS PED, CLIENTES AS CL, PRODUCTOS AS PROD WHERE (PEd.id_cliente = CL.id_cliente) AND (PED.ean = PROD.ean) AND (PED.cantidad_solicitada >= 45) ORDER BY num_pedido ASC; ``` ##### e) Determine quiénes son los 2 vendedores que menos facturan en el año 2019. Entregue sus nombres y apellidos. * Si no se agrupa por algo que se quiere en el select no sirve, ya que es un valor agregado. ```sql SELECT VEN.nombre, VEN.apellido, sum(FAC.total_facturado) AS facturado_2019 FROM FACTURAS AS FAC, PEDIDOS AS PED, VENDEDORES AS VEN WHERE (FAC.id_pedido = PED.id_pedido) AND (PED.id_vendedor = VEN.id_vendedor) AND (PED.fecha_pedido >= '01/01/2019') AND (PED.fecha_pedido <= '31/12/2019') GROUP BY (VEN.nombre, VEN.apellido) ORDER BY facturado_2019 ASC LIMIT 2; ``` ##### f) LINSA desea estrechar su relación con sus clientes estrellas, es decir los que generan más utilidades para la empresa. Determine cuáles son sus 2 mejores clientes. ¿Cuánta utilidad generan? ```sql SELECT CL.nombre, sum(FAC.total_facturado) AS utilidad FROM FACTURAS AS FAC, PEDIDOS AS PED, CLIENTES AS CL WHERE (FAC.id_pedido = PED.id_pedido) AND (CL.id_cliente = PED.id_cliente) GROUP BY (CL.nombre) ORDER BY utilidad DESC LIMIT 2; ``` ##### g) LINSA desea saber cuáles son los productos de categoría Mesa menos rentables (El término rentable se refiere a los que generan menor ingreso de esa categoría). Entrega EAN y nombre. ```sql SELECT PROD.ean, PROD.nombre, sum(FAC.total_facturado) AS ingreso FROM FACTURAS AS FAC, PEDIDOS AS PED, PRODUCTOS AS PROD WHERE (FAC.id_pedido = PED.id_pedido) AND (PED.ean = PROD.ean) AND (PROD.categoria = 'Mesa') GROUP BY (PROD.ean, PROD.nombre) ORDER BY ingreso ASC; ``` ##### h) Entregue el EAN y nombre de los 3 productos Mesa más rentables, en orden descendente (El término rentable se refiere a los que generan mayor ingreso de esa categoría). ```sql SELECT PROD.ean, PROD.nombre, sum(FAC.total_facturado) AS ingreso FROM FACTURAS AS FAC, PEDIDOS AS PED, PRODUCTOS as PROD WHERE (FAC.id_pedido = PED.id_pedido) AND (PED.ean = PROD.ean) AND (PROD.categoria = 'Mesa') GROUP BY (PROD.ean, PROD.nombre) ORDER BY ingreso DESC LIMIT 3; ``` ##### i) La empresa desea aumentar las ventas de las lámparas de la categoría Escritorio. Se desea entonces determinar cuáles son estos productos e identificar a los vendedores encargados (nombre y apellido) de al menos dos de los pedidos que tengan asociados una lámpara de tipo Escritorio. ```sql SELECT PROD.ean, PROD.nombre, VEN.id_vendedor, VEN.nombre, VEN.apellido, COUNT(PED.id_pedido) as n_pedidos FROM PRODUCTOS as PROD JOIN PEDIDOS as PED ON PED.ean=PROD.ean JOIN VENDEDORES as VEN on VEN.id_vendedor=PED.id_vendedor WHERE PROD.categoria = 'Escritorio' GROUP BY PROD.ean, PROD.nombre, VEN.id_vendedor, VEN.nombre, VEN.apellido HAVING COUNT (PED.id_pedido) >= 2 ORDER BY VEN.id_vendedor ASC; ``` ##### j) LINSA desea hacer un minucioso seguimiento de los productos que solicita el cliente al cual menos le ha facturado el 2019 (si no lo conoce, debe determinarlo primero). El seguimiento está orientado principalmente a los pedidos “no pagados”. Entregue todos los EAN y montos de los pedidos hechos, solo por este cliente, que no han sido pagados. ```sql SELECT CL.id_cliente, CL.nombre, SUM(PED.cantidad_solicitada*PED.precio_real) as total_facturado FROM PEDIDOS as PED JOIN FACTURAS as FAC ON FAC.id_pedido = PED.id_pedido JOIN CLIENTES as CL on PED.id_cliente = CL.id_cliente WHERE (FAC.fecha_facturacion >= '01/01/2019') AND (FAC.fecha_facturacion <= '31/12/2019') GROUP BY CL.id_cliente, CL.nombre ORDER BY total_facturado ASC LIMIT 1; -- Cliente que menos ha facturado (nombre: LamparasPY, id_cliente: 15) SELECT CL.id_cliente, PED.ean, FAC.id_factura, COB.fecha_pago, PED.id_pedido, (PED.cantidad_solicitada*PED.precio_real) as monto FROM COBRANZAS as COB JOIN FACTURAS as FAC ON COB.id_factura = FAC.id_factura JOIN PEDIDOS as PED ON FAC.id_pedido = PED.id_pedido JOIN CLIENTES as CL ON PED.id_cliente = CL.id_cliente WHERE COB.fecha_pago = 'No pagado' AND CL.id_cliente = 15 GROUP BY PED.ean, CL.id_cliente, COB.fecha_pago, FAC.id_factura, PED.id_pedido, monto ORDER BY monto DESC; ``` ##### k) Filtrar las facturas en base a todas aquellas * cuyo vendedor se llama “Pedro algo” * cuyos primeros 5 dígitos sean 17234 * Escriba la consulta(s) SQL que refleje lo que el trabajador desea hacer. * ¿A qué vendedor corresponde? ¿A cuántos pedidos podría corresponder, cuáles? ```sql SELECT PEDIDOS.id_pedido, PEDIDOS.EAN, PEDIDOS.fecha_pedido, VENDEDORES.nombre, VENDEDORES.apellido, FACTURAS.id_factura, FACTURAS.fecha_facturacion FROM PEDIDOS INNER JOIN VENDEDORES ON PEDIDOS.id_vendedor = VENDEDORES.id_vendedor INNER JOIN FACTURAS ON PEDIDOS.id_pedido = FACTURAS.id_pedido WHERE (VENDEDORES.nombre LIKE '%Pedro%') AND CAST(id_factura AS TEXT) LIKE '17234%'; ```

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully