MySQL Forums
Forum List  »  German

Re: SELECT mit Tagesintervall
Posted by: Thomas Wiedmann
Date: October 10, 2012 05:44AM

Hallo Mark,

sowas läßt sich am Besten mit einer Kalendertabelle und LEFT JOIN lösen. Dadurch das der Kalender alle Tage liefert, entsteht auch ein Datensatz für die Tage an denen keine Rechnung vorhanden ist.

CREATE TABLE invoice (
 id INT NOT NULL,
 invoicedate DATE NOT NULL,
 invoicenr INT NOT NULL,
 PRIMARY KEY (id)
);

INSERT INTO invoice VALUES
( 1, '2012-09-01', 2),
( 2, '2012-09-01', 3),
( 3, '2012-09-03', 1),
( 4, '2012-09-04', 6);


/* Kalendertabelle mit allen relevanten Tagen (z. B. ohne Sa, So, Feiertag, Urlaub) */
/* eventuell auch als Temporary Table */
CREATE TABLE kalender (
 kalenderDate DATE NOT NULL
);

INSERT INTO kalender VALUES
( '2012-09-01'),
( '2012-09-02'),
( '2012-09-03'),
( '2012-09-04'),
( '2012-09-05');


SELECT k.kalenderDate AS datum, 
       COUNT( DISTINCT (i.InvoiceNr)) AS bestellungen
  FROM kalender k
  LEFT JOIN invoice i
     ON i.invoicedate = k.kalenderdate
 WHERE i.InvoiceDate BETWEEN '2012-09-01 00:00:00' AND '2012-10-01 00:00:00'
    OR i.invoicedate IS NULL
GROUP BY k.kalenderDate; 
+------------+--------------+
| datum      | bestellungen |
+------------+--------------+
| 2012-09-01 |            2 |
| 2012-09-02 |            0 |
| 2012-09-03 |            1 |
| 2012-09-04 |            1 |
| 2012-09-05 |            0 |
+------------+--------------+
5 rows in set (0.02 sec)

mysql>

Grüße
Thomas

Options: ReplyQuote


Subject
Views
Written By
Posted
1481
October 10, 2012 04:31AM
Re: SELECT mit Tagesintervall
957
October 10, 2012 05:44AM


Sorry, you can't reply to this topic. It has been closed.

Content reproduced on this site is the property of the respective copyright holders. It is not reviewed in advance by Oracle and does not necessarily represent the opinion of Oracle or any other party.