如何从数据库中分组多行?

时间:2015-05-17 07:36:44

标签: sql sql-server database group-by

我希望在当晚之后将同一个晚上的所有药店分组到一个独特的行中。

select days.day, pharmacy.name
from days,
     pharmacy,
     pharmacy_night
where (pharmacy.Id_pharmacy in (SELECT Id_pharmacy
                                FROM pharmacy_in_region(@idregion))
  and pharmacy.Id_pharmacy = pharmacy_night.Id_pharmacy
  and days.Id_day = pharmacy_night.Id_day)

所需的输出:

row 1: Monday  Pharmacy1_pahrmacy5-
row 2: Tuesday pharmacy9_

2 个答案:

答案 0 :(得分:0)

使用现代显式JOIN语法重写。我想你想要像MySQL GROUP_CONCAT或类似的产品特定功能。 (没有指定dbms ...)

select days.day, GROUP_CONCAT(pharmacy.name)
from days
  join pharmacy_night on days.Id_day = pharmacy_night.Id_day
  join pharmacy on pharmacy.Id_pharmacy = pharmacy_night.Id_pharmacy
where pharmacy.Id_pharmacy in (SELECT Id_pharmacy
                               FROM pharmacy_in_region(@idregion))
group by days.day

答案 1 :(得分:0)

SELECT days.day
     , (STUFF((SELECT CAST(', ' + pharmacy.name AS VARCHAR(MAX)) 
         FROM pharmacy 
         WHERE (pharmacy.Id_pharmacy in (SELECT Id_pharmacy
                                FROM pharmacy_in_region(@idregion))
  and pharmacy.Id_pharmacy = pharmacy_night.Id_pharmacy
  and days.Id_day = pharmacy_night.Id_day)
         FOR XML PATH ('')), 1, 2, '')) AS Locations
FROM days,
     pharmacy_night

如果是sql server

,请尝试填充+ xml路径