我有查询:
select c.CustomerID 'Customer ID', c.CompanyName 'Company Name',
c.ContactName 'Contact Name', c.Address, c.City,
c.StateOrRegion 'State Or Region', c.PostalCode 'Postal Code',
c.Country, c.Phone, c.Fax, o.OrderID 'Order ID',
o.ShippedDate 'Shipped Date'
from orders o
left join Customers c
on o.customerid = c.customerid
where o.shippeddate is not null
order by c.ContactTitle asc
结果,我有:
SELECT e.id_taxe
, u.nm_user
, dt_taxe
, SUM(e.vl_taxe) as vl_taxe
FROM taxe as e
JOIN user as u
ON u.id_user = e.id_user
WHERE id_enterprise = 86
AND dt_taxe BETWEEN '2017-01-01' AND '2017-03-31'
AND lg_cancel = 0
GROUP
BY e.dt_taxe
, e.id_user
ORDER
BY e.id_user
, e.dt_taxe
如何连接行以获得结果:
id_taxe nm_user dt_taxe vl_taxe
728 Maria 2017-01-01 17091.07048034668
727 Maria 2017-02-01 14091.07048034668
721 Maria 2017-03-01 1021.07048034668
731 Pedro 2017-01-01 16353.569854736328
732 Pedro 2017-02-01 6353.56231239
答案 0 :(得分:0)
使用像PostgreSQL这样的数据库可以使用窗口函数来完成,但MySQL不支持窗口函数,所以你不能这样做
答案 1 :(得分:0)
此类操作通常最好在应用程序层完成。您的结果集不是非常SQLish,因为排序非常很重要。
但是,您可以使用变量执行此操作:
SELECT (CASE WHEN rn = 1 THEN id_taxe END) as id_taxe,
(CASE WHEN rn = 1 THEN nm_user END) as num_user,
dt_taxe, vl_taxe
FROM (SELECT eu.*,
(@rn := if(@u = e.id_user, @rn + 1,
if(@u := e.id_user, 1, 1)
)
) as rn
FROM (SELECT e.id_taxe, u.nm_user, e.dt_taxe, SUM(e.vl_taxe) as vl_taxe
FROM taxe e INNER JOIN
user u
ON u.id_user = e.id_user
WHERE id_enterprise = 86 AND
dt_taxe BETWEEN '2017-01-01' AND '2017-03-31' AND
lg_cancel = 0
GROUP BY e.dt_taxe, e.id_user
) eu CROSS JOIN
(SELECT @i := -1, @rn := 0)
ORDER BY id_user, dt_taxe
) eu;