简体   繁体   English

SQL查询-连接+计数

[英]SQL query - joins + counting

Here's my problem: I have a query that joins multiple tables to show details of some orders. 这是我的问题:我有一个查询,该查询连接多个表以显示某些订单的详细信息。 The query result in a table with columns: 查询结果在具有列的表中:

order ID | name | count | price | location | date

It's a hospital database and what i want to do is to add another column that says how many patients were at that location at given date. 这是一个医院数据库,我想做的是添加另一列,该列指出给定日期该位置有多少患者。

There's another table that shows patient stays - I need to count those. 还有一张表格显示了病人的住院时间-我需要计算一下。

patient ID | location | dateFrom | dateTo

The thing is that the STAYS table shows 2 dates - FROM and TO so I need to count every patient that was present at given location (ward) when order was placed. 事实是, STAYS表显示2个日期-FROM和TO,因此我需要对下订单时在给定位置(病房)中出现的每个患者进行计数。

Here's the initial query I need to update: 这是我需要更新的初始查询:

SELECT 
    AP_ZAMPOZ.ID_TOW AS IDTowaru, --merchandiseID
    GMSL_TOW.NAZWA_TOW AS Nazwa, --name
    GMSL_TOW.MNOZNIK_SYN AS Mnoznik, --quantity
    AP_ZAMPOZ.ZAM_CENA_S AS Cena, --price
    AP_ZAMPOZ.ZAM_IL AS Ilosc, --count
    AP_ZAMNAG.ZAM_DATE AS DataZam, --date
    GMSL_MAG.NAZWA_MAG AS Magazyn, --location
    APSL_TOW_PROD.PROD_NAZWA AS Producent, --producer
    APSL_TOW_ATC.NAZWA AS Grupa -group
FROM 
    AP_ZAMPOZ
JOIN 
    GMSL_TOW ON AP_ZAMPOZ.ID_TOW = GMSL_TOW.ID_TOW 
JOIN 
    AP_ZAMNAG ON AP_ZAMNAG.ZAM_ID_NAG = AP_ZAMPOZ.ZAM_ID_NAG
JOIN 
    GMSL_MAG ON AP_ZAMNAG.ID_MAG = GMSL_MAG.ID_MAG
JOIN 
    APSL_TOW ON AP_ZAMPOZ.ID_TOW = APSL_TOW.ID_TOW
LEFT JOIN 
    APSL_TOW_PROD ON APSL_TOW.ID_PROD = APSL_TOW_PROD.ID_PROD
LEFT JOIN 
    APSL_TOW_ATC ON APSL_TOW.KOD = APSL_TOW_ATC.KOD

The table with stays is called POBYT and has these relevant columns: 带有stays的表格称为POBYT ,具有以下相关列:

| ID_POB (ID) | IDK_JOS (location identifier) | DT_OD (date From) | DT_TO (date To)

Rows that I would like to see should look like those in my present query + number of patients at given location at given date. 我希望看到的行应类似于我当前的查询中的行+给定日期在给定位置的患者数。

Anyone have any ideas how to achieve this? 任何人有任何想法如何实现这一目标? I'm stuck... 我被困住了...

problem solved by adding subquery as another SELECT column. 通过将子查询添加为另一个SELECT列解决的问题。 Heres the code 继承人代码

SELECT

.
.
.
 APSL_TOW_ATC.NAZWA AS Grupa

(SELECT Count(*)
FROM pobyt 
WHERE (TO_DATE( AP_ZAMNAG.ZAM_DATE, 'YY/MM/DD')  >= TO_DATE(DT_OD, 'YY-MM-DD') AND (TO_DATE( AP_ZAMNAG.ZAM_DATE, 'YY/MM/DD')  <= TO_DATE(DT_DO, 'YY-MM-DD') OR dt_do IS NULL))
AND IDK_JOS = GMSL_MAG.KOD_MAG) AS LiczbaPacjentow --no. of patients at given date

FROM AP_ZAMPOZ
.
.
.

Works great. 效果很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM