我在下面有这个代码。我正在尝试根据日期合并行。
SELECT
TICKETS.TICKETID,
RECEIPTS.DATENEW,
TAXCATEGORIES.NAME = 'GCT' as GCT,
TAXCATEGORIES.NAME = 'Tax 25%' as Tax25,
TAXLINES.AMOUNT,
SUM(TAXLINES.AMOUNT) AS TOTAL,
SUM(CASE WHEN taxcategories.NAME = 'GCT' THEN taxlines.AMOUNT ELSE 0 END) AS GCTTOTAL,
SUM(CASE WHEN taxcategories.NAME = 'Tax 25%' THEN taxlines.AMOUNT ELSE 0 END) AS TAX25TOTAL
FROM
RECEIPTS,
TAXLINES,
TAXES,
TAXCATEGORIES,
TICKETS,
PAYMENTS
WHERE
PAYMENTS.RECEIPT = RECEIPTS.ID
AND RECEIPTS.ID = TAXLINES.RECEIPT
AND RECEIPTS.ID = TICKETS.ID
AND TAXLINES.TAXID = TAXES.ID
AND TAXES.CATEGORY = TAXCATEGORIES.ID
AND DATENEW >= '2016-07-14 00:00:00' AND DATENEW <= '2016-07-14 23:00:00'
GROUP BY gct, Tax25, CAST(RECEIPTS.DATENEW AS DATE)
现在我需要帮助将具有相同日期的行合并到一行中。我不知道我哪里出错了,我已经尝试了一系列连接但是我空白了。
答案 0 :(得分:1)
具有相同日期的记录似乎实际上在GCT
和Tax25
列的值不同。如果您从GROUP BY
子句中删除这些列,而是将它们汇总到SELECT
列表中,那么您将留下重复日期的单个记录。
请注意,在下面的查询中,我已使用显式内连接替换了您的隐式连接(使用逗号分隔的FROM
子句中的表),并使用ON
子句中的连接条件。这是现在编写查询的标准方法,它使它们更容易阅读。如果INNER JOIN
限制性太强,那么您可能打算使用LEFT JOIN
代替。
SELECT TICKETS.TICKETID,
RECEIPTS.DATENEW,
MAX(TAXCATEGORIES.NAME) = 'GCT' as GCT, -- one value per date
MAX(TAXCATEGORIES.NAME) = 'Tax 25%' as Tax25, -- one value per date
TAXLINES.AMOUNT,
SUM(TAXLINES.AMOUNT) AS TOTAL,
SUM(CASE WHEN taxcategories.NAME = 'GCT' THEN taxlines.AMOUNT ELSE 0 END) AS GCTTOTAL,
SUM(CASE WHEN taxcategories.NAME = 'Tax 25%' THEN taxlines.AMOUNT ELSE 0 END) AS TAX25TOTAL
FROM RECEIPTS
INNER JOIN TAXLINES
ON RECEIPTS.ID = TAXLINES.RECEIPT
INNER JOIN TAXES
ON TAXLINES.TAXID = TAXES.ID
INNER JOIN TAXCATEGORIES
ON TAXES.CATEGORY = TAXCATEGORIES.ID
INNER JOIN TICKETS
ON RECEIPTS.ID = TICKETS.ID
INNER JOIN PAYMENTS
ON PAYMENTS.RECEIPT = RECEIPTS.ID
WHERE DATENEW >= '2016-07-14 00:00:00' AND
DATENEW <= '2016-07-14 23:00:00'
GROUP BY CAST(RECEIPTS.DATENEW AS DATE)